Form1.csのソースプログラム
Form1.csのソースプログラムは以下となります。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace MyTcpListener
{
public partial class Form1 : Form
{
TcpListener server = null;
int gNo = 0;
bool fOK = true;
Int32 port;
IPAddress localAddr;
Byte[] bytes = new Byte[256];
String data = null;
TcpClient client;
NetworkStream stream;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Enabled = true;
button2.Enabled = false;
button3.Enabled = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (fOK) { TimeP(); }
}
private void button1_Click(object sender, EventArgs e)
{
port = Convert.ToInt32(textBox1.Text);
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
localAddr = ipHostInfo.AddressList[0];
server = new TcpListener(localAddr, port);
gNo = 1;
button1.Enabled = false;
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
gNo = 0;
server.Stop();
client.Close();
client = null;
button1.Enabled = true;
button2.Enabled = false;
button3.Enabled = false;
}
private void button3_Click(object sender, EventArgs e)
{
byte[] msg = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "\r\n");
stream.Write(msg, 0, msg.Length);
gNo = 3;
}
void TimeP()
{
fOK = false;
switch (gNo)
{
case 1:
textBox3.AppendText("接続待ち\r\n");
textBox3.AppendText("接続待ちで強制終了する場合は、タスクマネージャーを使用してください!!\r\n");
server.Start();
client = server.AcceptTcpClient();
textBox3.AppendText("接続完了\r\n");
stream = client.GetStream();
gNo = 3;
button3.Enabled = true;
break;
case 3:
if (stream.DataAvailable)
{
int i = stream.Read(bytes, 0, bytes.Length);
if (i != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
textBox3.AppendText(data);
}
}
break;
default:
break;
}
fOK = true;
}
}
}