【发布时间】:2013-03-06 08:17:55
【问题描述】:
我有一些客户端-服务器套接字代码,我希望能够构造和(重新)定期连接到相同的端点地址:localhost:17999
这里是服务器:
// Listen for a connection:
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Loopback, 17999);
Socket listener = new Socket(IPAddress.Loopback.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
listener.Bind(localEndPoint);
listener.Listen(1);
// Accept the connection and send a message:
Socket handler = listener.Accept();
byte[] bytes = new byte[1024];
bytes = Encoding.ASCII.GetBytes("The Message...");
handler.Send(bytes);
// Clean up
handler.Shutdown(SocketShutdown.Both);
handler.Close();
handler.Dispose();
listener.Shutdown(SocketShutdown.Both);
listener.Close();
listener.Dispose();
这里是客户端:
byte[] bytes = new byte[1024];
Socket receiver = new Socket(IPAddress.Loopback.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
receiver.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
receiver.Connect(new IPEndPoint(IPAddress.Loopback, 17999));
int num_bytes_received = receiver.Receive(bytes);
string result = Encoding.ASCII.GetString(bytes, 0, num_bytes_received);
receiver.Shutdown(SocketShutdown.Both);
receiver.Close();
receiver.Dispose();
当我第一次创建客户端和服务器时,它工作正常。但是,当我再次创建它时,出现错误:
"发送或接收数据的请求被拒绝,因为套接字是 未连接并且(当使用 sendto 在数据报套接字上发送时 call) 没有提供地址"
我希望能够在需要时按照以下事件顺序任意启动此机制:
- 启动服务器并等待接受连接
- 启动客户端并连接到服务器
- 在服务器上接受客户端连接
- 向客户端发送消息
- 必要时重复
我该怎么做?
提前致谢!
编辑:每次我构建客户端和服务器对象时,它都来自不同的进程。
【问题讨论】: