socket tcp 通讯 示例
private void button1_Click(object sender, EventArgs e)
{
Socket srv = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 8080);
srv.Bind(ep);
srv.Listen(100);
Thread th = new Thread(new ParameterizedThreadStart(GetConnection));
th.IsBackground = true;
th.Start(srv);
button1.Enabled = false;
}
private void GetConnection(object _srv)
{
Socket srv = (Socket)_srv;
while (true)
{
Socket client = srv.Accept();
Thread th = new Thread(new ParameterizedThreadStart(GetMesFromClient));
th.IsBackground = true;
th.Start(client);
}
}
private void GetMesFromClient(object _client)
{
Socket client = (Socket)_client;
while (true)
{
byte[] tmp = new byte[1024];
int len = client.Receive(tmp);
if (len == 0)
break;
byte[] buffer = new byte[len];
Array.Copy(tmp, buffer, len);
string mes = Encoding.Default.GetString(buffer);
int hd = client.Handle.ToInt32();
}
if (client != null)
{
client.Close();
}
}
{
Socket srv = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 8080);
srv.Bind(ep);
srv.Listen(100);
Thread th = new Thread(new ParameterizedThreadStart(GetConnection));
th.IsBackground = true;
th.Start(srv);
button1.Enabled = false;
}
private void GetConnection(object _srv)
{
Socket srv = (Socket)_srv;
while (true)
{
Socket client = srv.Accept();
Thread th = new Thread(new ParameterizedThreadStart(GetMesFromClient));
th.IsBackground = true;
th.Start(client);
}
}
private void GetMesFromClient(object _client)
{
Socket client = (Socket)_client;
while (true)
{
byte[] tmp = new byte[1024];
int len = client.Receive(tmp);
if (len == 0)
break;
byte[] buffer = new byte[len];
Array.Copy(tmp, buffer, len);
string mes = Encoding.Default.GetString(buffer);
int hd = client.Handle.ToInt32();
}
if (client != null)
{
client.Close();
}
}