服务端代码
static void Main(string[] args) { Socket server_socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); IPAddress ips = IPAddress.Parse("127.0.0.1"); IPEndPoint ipNode = new IPEndPoint(ips,6666); server_socket.Bind(ipNode); server_socket.Listen(40); Console.WriteLine("wait a client....."); Thread acceptThread = new Thread(AcceptThread); acceptThread.Start(server_socket); } static void AcceptThread(object obj) { Socket server_socket = (Socket)obj; while (true) { Socket client = server_socket.Accept(); Thread recvThread = new Thread(RecvThread); Thread sendThread = new Thread(SendThread); recvThread.Start(client); sendThread.Start(client); } } static void RecvThread(object client) { Socket clients = (Socket)client; while (true) { try { byte[] buffer = new byte[1024 * 1024]; int num = clients.Receive(buffer); string str = Encoding.ASCII.GetString(buffer, 0, num); Console.WriteLine(clients.RemoteEndPoint.ToString() + " : " + str); } catch (Exception ex) { Console.WriteLine(ex.Message+"65"); } } } static void SendThread(object objClient) { Socket client = (Socket)objClient; try { byte[] data = new byte[1024]; int recv = 0; string server_msg = "welcome! " + Thread.CurrentThread.ManagedThreadId; data = Encoding.ASCII.GetBytes(server_msg); client.Send(data, data.Length, SocketFlags.None); } catch (Exception ex) { Console.WriteLine(ex.Message+"85"); } }
客户端代码
static void Main(string[] args) { Socket client_socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); string ip = "127.0.0.1"; IPAddress ipAdress = IPAddress.Parse(ip); IPEndPoint ipEndpoint = new IPEndPoint(ipAdress,6666); client_socket.Connect(ipEndpoint); Thread recvThread = new Thread(RecvThread); recvThread.Start(client_socket); Thread sendThread = new Thread(SendThread); sendThread.Start(client_socket); } static void RecvThread(object obj) { Socket client_socket = (Socket)obj; try { byte[] data = new byte[1024]; int recv = 0; recv = client_socket.Receive(data); string msg; msg = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(msg + "客户端2"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } static void SendThread(object obj) { Socket client_socket = (Socket)obj; byte[] data = new byte[1024]; string msg = "收到服务端消息 客户端2"; data = Encoding.ASCII.GetBytes(msg); try { client_socket.Send(data, data.Length, SocketFlags.None); } catch(Exception ex) { Console.WriteLine(ex.Message); } }
以上是客户端和服务端的两个代码。考虑到并发的情况,所以使用线程去调用。但是服务端抛出了异常,远程主机强迫关闭了一个现有的连接。这是为什么?
你客户端执行完所有代码程序就结束了,服务器端肯定报 远程主机终端,
你在Main函数最后一行加入Console.ReadLine(); 或者ReadKey()来阻止程序结束,
你需要理解一下控制台程序的执行逻辑, 当Main里面的代码执行完,此程序就结束, 主程序都结束了,你的2个线程也就死了
你的客户端并发有问题,你可以先阻塞发送,等待接受完成的指令
或者
服务端保持长连接
关闭连接是正常的,一边关闭了,另外一边就被强迫关闭了。