2
我試圖通過套接字連接將數據從客戶端發送到服務器。我成功發送第一個數據,但當我嘗試發送第二個它永遠不會發送,當我嘗試發送第三個它給我Sockets.SocketException
我該如何解決?服務器/客戶端套接字連接
服務器
byte[] buffer = new byte[1000];
IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = iphostInfo.AddressList[0];
IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 8080);
Socket sock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(localEndpoint);
sock.Listen(5);
while (true) {
Socket confd = sock.Accept();
string data = null;
int b = confd.Receive(buffer);
data += Encoding.ASCII.GetString(buffer, 0, b);
Console.WriteLine("" + data);
confd.Close();
}
客戶
byte[] data = new byte[10];
IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAdress = iphostInfo.AddressList[0];
IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 8080);
Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try {
client.Connect(ipEndpoint);
Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString());
while (true) {
string message = Console.ReadLine();
byte [] sendmsg = Encoding.ASCII.GetBytes(message);
int n = client.Send(sendmsg);
}
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
Console.WriteLine("Transmission end.");
Console.ReadKey();
因爲在您的服務器上連接後,您會收到1個字符串,並關閉連接。 – BugFinder
但是我們不是再次打開嗎? – Pareidolia
你的客戶不顯示任何形式的關閉...所以跟蹤你的代碼,它會告訴你什麼是錯的 – BugFinder