操作不允许对非连接的插座 - C#4.0不允许、插座、操作

2023-09-08 09:42:13 作者:十年戎马心孤单

它保持其操作的非连接的插座不准就行了一个错误

 的NetworkStream ServerStream = Connect2Server.GetStream();
 

和我真的不知道为什么

下面是休息的code为该函数

  INT缓冲区大小= 0;
ASCIIEncoding Convert2Tet =新ASCIIEncoding();
TcpClient的Connect2Server =新的TcpClient();
IPEndPoint ServerEndPoint =新IPEndPoint(IPAddress.Parse(127.0.0.1),8801);
的NetworkStream ServerStream = Connect2Server.GetStream();
Console.WriteLine(连接到服务器);
Connect2Server.Connect(ServerEndPoint);
byte []的WelcomeMessage =新的字节[4096];
ServerStream.Read(WelcomeMessage,0,4096);
Console.Write(Convert2Tet.GetChars(WelcomeMessage));
字符串UserCredentials =到Console.ReadLine();
缓冲区大小= Convert2Tet.GetByteCount(UserCredentials);
byte []的证书=新的字节[缓冲区大小]
证书= Convert2Tet.GetBytes(UserCredentials);
ServerStream.Write(凭证,0,缓冲区大小);
 

解决方案 插座两孔和三孔有啥不一样 看完全明白

您得连接()之前,你可以得到的NetworkStream。

该文档通常是pretty的好,这个还挺东西。在例外的帮助GetStream,你会看到:

  

InvalidOperationException异常:该   TcpClient的未连接到远程   主机。

It keeps having an error "Operation not allowed on non-connected sockets" on the line

NetworkStream ServerStream = Connect2Server.GetStream();

And I'm not really sure why

Below is rest of the code for that function

int buffersize = 0;
ASCIIEncoding Convert2Tet = new ASCIIEncoding();
TcpClient Connect2Server = new TcpClient();
IPEndPoint ServerEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8801);
NetworkStream ServerStream = Connect2Server.GetStream();
Console.WriteLine("Connecting to Server");
Connect2Server.Connect(ServerEndPoint);
byte[] WelcomeMessage = new byte[4096];
ServerStream.Read(WelcomeMessage, 0, 4096);
Console.Write(Convert2Tet.GetChars(WelcomeMessage));
string UserCredentials = Console.ReadLine();
buffersize = Convert2Tet.GetByteCount(UserCredentials);
byte[] Credentials = new byte[buffersize];
Credentials = Convert2Tet.GetBytes(UserCredentials);
ServerStream.Write(Credentials, 0, buffersize);

解决方案

You gotta Connect() before you can get the NetworkStream.

The documentation is usually pretty good for this kinda stuff. Under Exceptions in the help for GetStream, you'll see:

InvalidOperationException: The TcpClient is not connected to a remote host.