Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
846 views
in Technique[技术] by (71.8m points)

.net 4.0 - Operation not allowed on non-connected Sockets - C# 4.0

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

var ServerStream = Connect2Server.GetStream();

And I'm not really sure why

Below is rest of the code for that function

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...