我在等待数据的地方创建了服务器。当我调用AcceptAsync
时,调用处理方法connectArgs_Accepted
,即使方法为空,也会导致异常并崩溃。怎么处理?
Thread thread = new Thread(new ThreadStart(connect));
thread.Start();
}
Socket connection;
SocketAsyncEventArgs connectArgs;
string ip = "192.168.0.13";
int port = 13001;
private void connect() {
connectArgs = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint(ip, port) };
connectArgs.Completed += connectArgs_Accepted;
connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connection.AcceptAsync(connectArgs);
}
void connectArgs_Accepted(object sender, SocketAsyncEventArgs e) {//that causes exception
/* if (e.SocketError == SocketError.Success) {
// data sent
try {
Receive();
} catch (Exception ex) { Console.WriteLine(ex); }
} else {
// error
}*/
}
输出:
System.InvalidOperationException: Socket must be bound to a local endpoint to perform this operation.
at System.Net.Sockets.Socket.AcceptAsync(SocketAsyncEventArgs e)
at HomeSecurityClient.JPGServer.connect()
The thread 0x458 has exited with code 259 (0x103).
。 客户端(发件人)
namespace HomeSecurity {
//singleton
public class JPGClient {
IPAddress ip;
int port;
public static JPGClient JPG_CLIENT = null;
public JPGClient(IPAddress ip, int port) {
this.ip = ip;
this.port = port + 1;
JPG_CLIENT = this;
Thread thread = new Thread(new ThreadStart(sendjpg));
thread.Start();
}
public void sendjpg() {
TcpClient client = new TcpClient();
try {
System.Diagnostics.Debug.WriteLine(ip + " X " + 13001);
client.Connect(ip, 13001);
System.Diagnostics.Debug.WriteLine(ip + " polaczzyl X " + 13001);
// Retrieve the network stream.
NetworkStream stream = client.GetStream();
ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(new Uri(@"C:\a.jpg", UriKind.Absolute));
MessageData data = new MessageData(imageBrush);
IFormatter formatter = new BinaryFormatter();
while (true) {
System.Diagnostics.Debug.WriteLine("SLEEEEEEEEEEEEEEE");
formatter.Serialize(stream, data);
Thread.Sleep(1000);
// data.GetNewImage();
}
} catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); }
}
}
}
答案 0 :(得分:0)
服务器套接字(接受客户端连接)应首先绑定到本地网络接口和端口。 在调用AcceptAsync之前,您应该将socket绑定到本地端点。
查看Socket.Bind信息(http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.bind(v=vs.110).aspx)