【发布时间】:2011-06-27 20:16:34
【问题描述】:
我有一个项目,我试图将序列化对象发送到服务器,然后等待“OK”或“ERROR”消息返回。
我似乎遇到了与以下海报类似的问题:TcpClient send/close problem
问题是我似乎能够发送原始对象的唯一方法是关闭连接,但是(当然)我迫不及待地想看看服务器是否成功处理了对象。
private void button4_Click(object sender, EventArgs e)
{
RequestPacket req = new RequestPacket();
/// ... Fill out request packet ...
/// Connect to the SERVER to send the message...
TcpClient Client = new TcpClient("localhost", 10287);
using (NetworkStream ns = Client.GetStream())
{
XmlSerializer xml = new XmlSerializer(typeof(RequestPacket));
xml.Serialize(ns, req);
/// NOTE: This doesn't seem to do anything....
/// The server doesn't get the object I just serialized.
/// However, if I use ns.Close() it does...
/// but then I can't get the response.
ns.Flush();
// Get the response. It should be "OK".
ResponsePacket resp;
XmlSerializer xml2 = new XmlSerializer(typeof(ResponsePacket));
resp = (ResponsePacket)xml2.Deserialize(ns);
/// ... EVALUATE RESPONSE ...
}
Client.Close()
}
更新:回应一位评论者,我认为客户不会有错。它只是在等待对象,并且对象永远不会出现,直到我关闭套接字....但是,如果我错了,我会很乐意公开吃乌鸦。 =) 这是客户端:
static void Main(string[] args)
{
// Read the port from the command line, use 10287 for default
CMD cmd = new CMD(args);
int port = 10287;
if (cmd.ContainsKey("p")) port = Convert.ToInt32(cmd["p"]);
TcpListener l = new TcpListener(port);
l.Start();
while (true)
{
// Wait for a socket connection.
TcpClient c = l.AcceptTcpClient();
Thread T = new Thread(ProcessSocket);
T.Start(c);
}
}
static void ProcessSocket(object c)
{
TcpClient C = (TcpClient)c;
try
{
RequestPacket rp;
//// Handle the request here.
using (NetworkStream ns = C.GetStream())
{
XmlSerializer xml = new XmlSerializer(typeof(RequestPacket));
rp = (RequestPacket)xml.Deserialize(ns);
}
ProcessPacket(rp);
}
catch
{
// not much to do except ignore it and go on.
}
}
是的....就是这么简单。
【问题讨论】:
-
1.是否调用 ProcessPacket? 2. ProcessSocket 中是否抛出任何异常(至少将异常写入日志或控制台。不要只是吃掉它)。 3. 响应是如何发回的?
-
ProcessPacket 行永远不会被命中。我在那里有一个断点。
-
您是否尝试过使用
C.GetStream().Read()代替?您是否尝试过记录您确实得到的异常?阅读面向流与面向消息的传输协议,您就会明白为什么。 -
A) 我没有遇到异常。我什么也得不到。 B) C.GetStream().Read() 与我所做的有何不同? C)我已经把它分解成它的核心元素(Read(byteBuffer),Write(byteBuffer),WriteLine(byteBuffer)......)无济于事。
-
您是否尝试过进行 WireShark 捕获以准确查看字节何时通过网络发送(这将需要在一台机器上运行客户端并在另一台机器上运行服务器)?有可能数据正在物理上被发送,但接收流正在缓冲该数据并且在连接被发起者终止之前不释放它。
标签: c# sockets tcp tcpclient networkstream