问题描述
各位大神,求帮助
解决方案
解决方案二:
定义两个Socket,A绑定端口并监听,B发起连接,并发送消息,A再接受消息,over.具体实现网上代码太多。
解决方案三:
服务器端:intport=6000;stringhost="127.0.0.1";IPAddressip=IPAddress.Parse(host);IPEndPointipe=newIPEndPoint(ip,port);SocketsSocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);sSocket.Bind(ipe);sSocket.Listen(0);Console.WriteLine("监听已经打开,请等待");//receivemessageSocketserverSocket=sSocket.Accept();Console.WriteLine("连接已经建立");stringrecStr="";byte[]recByte=newbyte[4096];intbytes=serverSocket.Receive(recByte,recByte.Length,0);recStr+=Encoding.ASCII.GetString(recByte,0,bytes);//sendmessageConsole.WriteLine("服务器端获得信息:{0}",recStr);stringsendStr="sendtoclient:hello";byte[]sendByte=Encoding.ASCII.GetBytes(sendStr);serverSocket.Send(sendByte,sendByte.Length,0);serverSocket.Close();sSocket.Close();
客户端intport=6000;stringhost="127.0.0.1";//服务器端ip地址IPAddressip=IPAddress.Parse(host);IPEndPointipe=newIPEndPoint(ip,port);SocketclientSocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);clientSocket.Connect(ipe);//sendmessagestringsendStr="sendtoserver:hello,nihao";byte[]sendBytes=Encoding.ASCII.GetBytes(sendStr);clientSocket.Send(sendBytes);//receivemessagestringrecStr="";byte[]recBytes=newbyte[4096];intbytes=clientSocket.Receive(recBytes,recBytes.Length,0);recStr+=Encoding.ASCII.GetString(recBytes,0,bytes);Console.WriteLine(recStr);clientSocket.Close();