测试代码:
客户端:
public partial class Form1 : Form { Socket myClientSocket; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { button1.Text = "发送"; } private void button1_Click(object sender, EventArgs e) { myClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.105"), 49392); myClientSocket.Connect(ipEndPoint); string sendMessage = "123"; byte[] mybyte = System.Text.Encoding.GetEncoding("gb2312").GetBytes(sendMessage); myClientSocket.Send(mybyte); byte[] receivebyte = new byte[1024]; myClientSocket.Receive(receivebyte); textBox1.Text = System.Text.Encoding.GetEncoding("gb2312").GetString(receivebyte); } }
服务器端:
public partial class Form1 : Form { Socket listenServerSocket; Socket socket; public Form1() { InitializeComponent(); listenServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listenServerSocket.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.105"), 49392)); listenServerSocket.Listen(10); listenServerSocket.BeginAccept(new AsyncCallback(OnConnectRequest), listenServerSocket); } public void OnConnectRequest(IAsyncResult ar) { //初始化一个SOCKET,用于其它客户端的连接 Socket server1 = (Socket)ar.AsyncState; socket = server1.EndAccept(ar); //将要发送给连接上来的客户端的提示字符串 string strDateLine = textBox1.Text; Byte[] byteDateLine = System.Text.Encoding.GetEncoding("gb2312").GetBytes(strDateLine); //将提示信息发送给客户端 socket.Send(byteDateLine, byteDateLine.Length, 0); //等待新的客户端连接 server1.BeginAccept(new AsyncCallback(OnConnectRequest), server1); while (true) { int recv = socket.Receive(byteDateLine); string stringdata = Encoding.GetEncoding("gb2312").GetString(byteDateLine, 0, recv); DateTimeOffset now = DateTimeOffset.Now; //获取客户端的IP和端口 string ip = socket.RemoteEndPoint.ToString(); if (stringdata == "STOP") { //当客户端终止连接时 MessageBox.Show(ip + "已从服务器断开"); break; } } } }