Operation not allowed on non-connected sockets

  • Thread starter Thread starter Curious
  • Start date Start date
C

Curious

Hi,

I am using the following code to transfer messages between client and
server.

Upon running that code I am getting the following error message in
method ReceiveFromClient on line Stream s =....
"An unhandled exception of type 'System.InvalidOperationException'
occurred in system.dll

Additional information: Operation not allowed on non-connected
sockets."

The message "Welcome from client" is shown in console.

Can someone help me solve the problem.
Thanks in Advance


class Class1
{
public static string ReceiveFromClient(ref TcpClient clientSocket)
{
XmlSerializer ser = new XmlSerializer(typeof(string));
Stream s = clientSocket.GetStream();
string dt = (string) ser.Deserialize(s);
s.Close();

return dt;
}

public static void SendToClient(string transfer, ref TcpClient
clientSocket)
{
XmlSerializer ser = new XmlSerializer(typeof(string ));
Stream s = clientSocket.GetStream();
ser.Serialize(s, transfer);
s.Close();
} // end method SendToClient

public static void Server()
{
TcpListener listener = new TcpListener(new
IPEndPoint(IPAddress.Parse("127.0.0.1"), 5500));
listener.Start();
TcpClient client = listener.AcceptTcpClient();

string msg = ReceiveFromClient(ref client);
Console.WriteLine("1 - {0}", msg);
SendToClient("Hello World from server", ref client);
}

[STAThread]
static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(Class1.Server));
t.IsBackground = true;
t.Start();

TcpClient client = new TcpClient();
client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5500));

SendToClient("Welcome from client", ref client);
string msg = ReceiveFromClient(ref client);
Console.WriteLine("2 - {0}", msg);

Console.ReadLine();
}
}
 
You closed the stream in ReceiveFromClient and then tried to use it in
SendToClient (and vise versa).
 
If I do not close both streams, application blocks and no message
arrives.
If I do not close in ReceiveFromClient, error as previous is given.
If I do not close in SendToClient, application blocks and no message
arrives.

Can some further help be given.
 
Curious said:
If I do not close both streams, application blocks and no message
arrives.
If I do not close in ReceiveFromClient, error as previous is given.
If I do not close in SendToClient, application blocks and no message
arrives.

Can some further help be given.

1) You probably need to flush the stream rather than close it.

2) You are confusing yourself and everyone else by calling functions called
ReceiveFromClient and SendToClient in the client. Thus making it unclear
whether it is the client or the server that is having the problem.

3) All use of ref is unnecessary - It is only needed if you need to write
"clientSocket=xxxx" in the method.

4) There is no gaurantee that the server thread has even created the socket
let alone started listening on it when you first send.
 
Back
Top