C# C“TCP客户”;不允许在未连接的插座上进行操作。”;
我的目标是创建一个保持连接的TcpClient,允许将消息发送到服务器,并具有一个定时监视器,在特定空闲频率期间向服务器发送特殊消息。还没走多远就被难倒了 对于当前代码,使用console tester应用程序发送的第一条消息接收良好,但在发送另一条消息时,会引发异常,并显示消息“不允许在未连接的套接字上进行操作” 我已尝试删除stream.Dispose()行,在第二次尝试期间它将挂起在stream.Read(…)上。我还尝试使NetworkStream成为该类的成员,并在构造函数中将其设置为client.GetStream(),在第二次尝试期间,它将挂起stream.Read(…)C# C“TCP客户”;不允许在未连接的插座上进行操作。”;,c#,tcpclient,C#,Tcpclient,我的目标是创建一个保持连接的TcpClient,允许将消息发送到服务器,并具有一个定时监视器,在特定空闲频率期间向服务器发送特殊消息。还没走多远就被难倒了 对于当前代码,使用console tester应用程序发送的第一条消息接收良好,但在发送另一条消息时,会引发异常,并显示消息“不允许在未连接的套接字上进行操作” 我已尝试删除stream.Dispose()行,在第二次尝试期间它将挂起在stream.Read(…)上。我还尝试使NetworkStream成为该类的成员,并在构造函数中将其设置为
public class TcpClientTest
{
private TcpClient client = new TcpClient();
private string hostName;
private int port;
public TcpClientTest(string hostName, int port)
{
this.hostName = hostName;
this.port = port;
client.Connect(hostName, port);
}
public byte[] SendMessage(string name, string message)
{
if (client == null) throw new Exception("Client connection has not been established");
Person person = new Person();
person.Name = name; person.Message = message;
byte[] messageBytes = (System.Text.Encoding.Unicode.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(person)));
const int bytesize = 1024 * 1024;
try
{
NetworkStream stream = client.GetStream();
if (stream != null)
{
stream.Write(messageBytes, 0, messageBytes.Length); // Write the bytes
messageBytes = new byte[bytesize]; // Clear the message
// Receive the stream of bytes
stream.Read(messageBytes, 0, messageBytes.Length);
}
// Clean up
stream.Flush();
stream.Dispose();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return messageBytes; // Return response
}
}
// In console tester app
static void Main(string[] args)
{
TcpClientTest client = new TcpClientTest("127.0.0.1", 1234);
string exit = "2";
do
{
if (exit == "1") client.SendMessage("TEST", "TEST");
Console.WriteLine("1 Send Message 2 Exit");
exit = Console.ReadLine();
} while (exit != "2");
}
当然,不要在那个流上处理。除此之外,不看更多代码就无法诊断。你说这段代码在你第一次调用它时起作用,但在第二次调用时不起作用。在这两次操作之间你做什么?当你处理流时,它会关闭连接。您也应该将tcpclient连接移动到该函数,或者仅在完成注释调整后才处理tcpclient,因为您无法可靠地执行
stream.Read(messageBytes,0,messageBytes.Length)
,仅仅因为你要求messageBytes.Length
字节,并不意味着你将得到messageBytes.Length
的填写,还有一个发送(
由发送方可以分为多个读取(
由接收方)(事实上,两个发送也可以合并为一个读取)。您必须使用某种类型的并反复呼叫读取
,直到获得您要查找的完整消息。我添加了一个编辑,以包括调用SendMessage之间发生的事情…因为您看不到太多。