我有一个项目,我试图将序列化对象发送到服务器,然后等待“OK”或“ERROR”消息返回。
我似乎遇到了与海报类似的问题:TcpClient发送/关闭问题
问题是,我似乎能够发送原始对象的唯一方法是关闭连接,但是(当然)我迫不及待地想看看服务器是否成功处理了该对象。
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.
}
}
是啊……就这么简单。
呃哦,你可以责怪内格尔算法。但它与 C# 无关,它是 TCP/IP 堆栈的默认行为。使能够NoDelay套接字选项使用设置套接字选项方法。但要小心,禁用 Nagle 算法会降低吞吐量。
我也不确定您在套接字上使用的流,因为我根本不是 C# 开发人员,但尝试删除它的实例,以便它确实可以写入:-)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)