服务器:
Socket sokWatch = null;
Thread thread = null;
private void button1_Click(object sender, EventArgs e)
{
//创建监听的套接字
sokWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建IP地址
IPAddress address =IPAddress.Parse(txtIP.Text.Trim());
//创建端口地址
IPEndPoint post = new IPEndPoint(address, int.Parse(txtPost.Text.Trim()));
//将监听器绑定在端口上
sokWatch.Bind(post);
//端口同时连接上限为10
sokWatch.Listen(10);
//多线程来处理服务器等待连接
thread = new Thread(getAccept);
thread.Start();
ShowMsg("服务器正在监听客户响应........!");
}
void getAccept()
{
Socket sockConnection = sokWatch.Accept();
ShowMsg("有客户端接入!");
}
void ShowMsg(string msg)
{
txtMsg.AppendText(msg+"\r\n");
}
客户端:
IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPost.Text.Trim()));
Socket sokConnection = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
sokConnection.Connect(endpoint);
|
|