我试图在客户端程序和服务器程序之间建立连接。 从客户端向服务器发送数据工作正常,但我不知道如何立即从服务器向客户端发回回复。 例如,在这种情况下,我有一个程序用于酒店存储所有预订(服务器)和客户程序,以便人们可以查看他们的预订。客户端程序将客户端的ID发送到服务器,并且需要发回该客户端预留的序列化Hashtable。
我的客户端代码如下所示:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
const int POORT = 4001;
IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
socket.Connect(new IPEndPoint(ipaddress, POORT));
using (NetworkStream ns = new NetworkStream(socket)) {
using (StreamWriter sw = new StreamWriter(ns)) {
sw.WriteLine(klantId);
sw.Flush();
}
}
socket.Shutdown(SocketShutdown.Both);
socket.Close();
我的服务器代码:
IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
IPEndPoint ep = new IPEndPoint(ipaddress, 4001);
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(ep);
serverSocket.Listen(50);
try {
string klantid;
while (true) {
using (Socket clientSocket = serverSocket.Accept()) {
using (NetworkStream ns = new NetworkStream(clientSocket)) {
using (StreamReader sr = new StreamReader(ns)) {
klantid = sr.ReadLine();
// Searches the reservations
Hashtable reservaties = hotel.ReservatiesZoeken(int.Parse(klantid));
// Tried this to send the data. Doesn't seem to work.
using (MemoryStream stream = new MemoryStream()) {
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, reservaties);
stream.Flush();
}
}
}
}
}
}
finally {
serverSocket.Shutdown(SocketShutdown.Both);
serverSocket.Close();
}
我想我可以在客户端实现一个监听器并建立从服务器到客户端的新连接,但我无法帮助,但我觉得应该可以通过与之相同的连接发送回复。请求。
答案 0 :(得分:0)
您在发送ID后立即关闭客户端上的套接字。您需要保持打开状态并等待服务器发送数据,例如:
Socket socket = new Socket(AddressFamily.InterNetwork, ...);
// open and send ID
int dataAvailable = 0;
while (dataAvailable == 0 || dataAvailable != socket.Available)
{
dataAvailable = socket.Available;
Thread.Sleep(100); // if no new data after 100ms assume transmission finished
}
var data = new byte[dataAvailable];
socket.Receive(data);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
免责声明:这不是“生产就绪代码”,应该只是提示您如何解决问题。通常情况下,“等待100毫秒”部分不应在生产代码中使用......