非连接套接字上不允许操作 - C#4.0

时间:2010-11-13 00:56:27

标签: c# .net-4.0 tcp networkstream

它在行

上一直出现“非连接套接字上不允许操作”的错误
var ServerStream = Connect2Server.GetStream();

我不确定为什么

以下是该功能的其余代码

var buffersize = 0;
var Convert2Tet = new ASCIIEncoding();
var Connect2Server = new TcpClient();
var ServerEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8801);
var ServerStream = Connect2Server.GetStream();

Console.WriteLine("Connecting to Server");

Connect2Server.Connect(ServerEndPoint);
var WelcomeMessage = new byte[4096];
ServerStream.Read(WelcomeMessage, 0, 4096);

Console.Write(Convert2Tet.GetChars(WelcomeMessage));

var UserCredentials = Console.ReadLine();
buffersize = Convert2Tet.GetByteCount(UserCredentials);

var Credentials = new byte[buffersize];
Credentials = Convert2Tet.GetBytes(UserCredentials);

ServerStream.Write(Credentials, 0, buffersize);

1 个答案:

答案 0 :(得分:14)

在获得NetworkStream之前,你必须连接()。

文档通常对这种东西很好。在GetStream的帮助中的例外下,您会看到:

  

InvalidOperationException:The   TcpClient未连接到远程   主机。