Socket Send/Receive problem

E

EppO

I wrote a small server/client app. I created a class for my customized
socket object using (synchronous) Sockets functions for both server
and client use.
When client connects to server, if It sends something to server,
everything works fine (i.e. server received what client sent). But if
I try to make server send anything, client receive 0 byte although
server send a correct bytes size.

Any idea ?

When I send/receive in server side, I use client socket what I get
when serverSock.Accept();

[Server Side]
clientSock = serverSock.Accept();
int bytesSent = clientSock.Send(buffer, buffer.Length,
SocketFlags.None);
=> bytesSent > 0

[Client Side]
clientSock.Connect();
int bytesReceived = client.Receive(buffer, 0, clientSock.Available,
SocketFlags.None);
=> bytesReceived = 0 !!

If I send in client and receive in server instead, it works...
 
G

Guest

That line was the origin of my troubles
_sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1)

I don't know exactly why... ReuseAddress was a socket option I knew of my old unix C network programming years

But another problem occured when I close connection and try to make another connection. With this code, the next time I try to connect, client receive 0 byte... (I try to connect to ftp or ssh port for example)

private void buttonConnect_Click(object sender, System.EventArgs e

Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)
EndPoint server = new IPEndPoint(IPAddress.Parse(textBoxAddress.Text), Convert.ToInt32(textBoxPort.Text))
sock.Connect(server)
textBoxLog.Text += "Connected to " + server.ToString() + "\r\n"
byte[] buffer = new byte[sock.Available]
int bytesReceived = sock.Receive(buffer, 0, sock.Available, SocketFlags.None)
textBoxLog.Text += bytesReceived.ToString() + " bytes received: \r\n" + Encoding.ASCII.GetString(buffer) + "\r\n"
sock.Shutdown(SocketShutdown.Both)
sock.Close()
sock = null


When I click 2 times the button, first time works but not next.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top