你好,请问网络编程聊天室程序运行后出错,服务器端显示 accept:invalid argument.这个问题你解决了吗?
答案:2 悬赏:40 手机版
解决时间 2021-03-20 09:00
- 提问者网友:我们很暧昧
- 2021-03-19 11:08
课程设计,希望你可以帮我一下
最佳答案
- 五星知识达人网友:猎心人
- 2021-03-19 12:22
参数不正确
全部回答
- 1楼网友:傲气稳了全场
- 2021-03-19 12:57
这样的写法有点问题:1)服务器端既然采用了异步方式Accept,就没有必要再启线程2)估计allDone是一个ManualResetEvent。用ManualResetEvent的目的什么呢?服务器端采用异步Accept的代码其实很简单,也不需要ManualResetEvent同步 public class AppTCPServer { public AppTCPServer(string localIP, int port) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); EndPoint localEP = new IPEndPoint(IPAddress.Parse(localIP), port); socket.Bind(localEP); socket.Listen(100); socket.BeginAccept(AcceptAsync, socket); } private void AcceptAsync(IAsyncResult ar) { Socket socket = ar.AsyncState as Socket; try { Socket client = socket.EndAccept(ar); Console.WriteLine("客户端连接成功!客户端:{0}", client.RemoteEndPoint.ToString()); if (OnConnected != null) { OnConnected(this, new ClientConnectedEventArgs(client)); } } catch (Exception e) { Console.WriteLine("AcceptAsync发生异常,异常信息:\n{0}", e.Message); } finally { //继续异步Accept socket.BeginAccept(AcceptAsync, socket); } } //客户端连接后的事件 OnConnect public event EventHandler OnConnected; } /// /// 事件参数:接收客户端连接后的事件参数 /// public class ClientConnectedEventArgs : EventArgs { public ClientConnectedEventArgs(Socket clientSocket) { ClientSocket = clientSocket; } public Socket ClientSocket { get; private set; } } class Program { static void Main(string[] args) { AppTCPServer server = new AppTCPServer("127.0.0.01", 8000); server.OnConnected += server_OnConnected; Console.WriteLine("按任意键结束程序……"); Console.ReadKey(); } static void server_OnConnected(object sender, ClientConnectedEventArgs e) { Socket client = e.ClientSocket; string hello = "Hello from AppTCPServer"; client.Send(Encoding.Default.GetBytes(hello)); } } 客户端测试程序 class Program { static void Main(string[] args) { //模拟100个客户连接服务器 for (int i = 0; i < 100; i++) { Socket socket = ConnectToServer("127.0.0.1", 8000); byte[] buffer = new byte[1024]; int bytesRecevied = socket.Receive(buffer, buffer.Length, SocketFlags.None); byte[] messageBytes = new byte[bytesRecevied]; Array.Copy(buffer, messageBytes, bytesRecevied); Console.WriteLine(Encoding.Default.GetString(messageBytes)); socket.Disconnect(false); socket.Close(); } Console.ReadKey(); static Socket ConnectToServer(string serverIP, int serverPort) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); EndPoint localEP = new IPEndPoint(IPAddress.Any, 0); socket.Bind(localEP); socket.Connect(new IPEndPoint(IPAddress.Parse(serverIP), serverPort)); return socket; } }
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯