Socket通讯成功案例
Socket通讯案例
#region 服务端
//int port = 1234;
//string host = "127.0.0.1";
//IPAddress ip = IPAddress.Parse(host);
//IPEndPoint ipe = new IPEndPoint(ip, port);
//Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//sSocket.Bind(ipe);
//sSocket.Listen(0);
//Console.WriteLine("监听已经打开,请等待");
////receive message
//Socket serverSocket = sSocket.Accept();
//Console.WriteLine("连接已经建立");
//string recStr = "";
//byte[] recByte = new byte[4096];
//int bytes = serverSocket.Receive(recByte, recByte.Length, 0);
//recStr += Encoding.ASCII.GetString(recByte, 0, bytes);
//////send message
//Console.WriteLine("服务器端获得信息:{0}", recStr);
//string sendStr = "send to client :hello";
//byte[] sendByte = Encoding.ASCII.GetBytes(recStr);
//serverSocket.Send(sendByte, sendByte.Length, 0);
//serverSocket.Close();
//sSocket.Close();
#endregion
客户端(调用服务端即向服务端发消息)
#region Socket
//int port = 1234;
//string host = "127.0.0.1";//服务器端ip地址
//IPAddress ip = IPAddress.Parse(host);
//IPEndPoint ipe = new IPEndPoint(ip, port);
//Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//clientSocket.Connect(ipe);
////send message
////string sendStr = "begin#70";
//string sendStr = this.tbxinput.Text;
//byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
//clientSocket.Send(sendBytes);
////receive message
//string recStr = "";
//byte[] recBytes = new byte[4096];
//int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);
//recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);
//Console.WriteLine(recStr);
//this.rtbOutput.Text = recStr;
//clientSocket.Close();
#endregion