开发者

Problem about socket communication

I have two separate socket projects in VS.NET. One of them is sender, other one is receiver. After starting receiver, i send data from sender. Although send method returns 13 bytes as successfully trans开发者_C百科ferred, the receiver receives 0 (zero). The receiver accepts sender socket and listens to it. But cannot receive data. Why?

P.S. : If sender code is put in receiver project, receiver can get data, as well.


I think the problem is that the send application is ending before the receiver can read the data. If you put a Thread.Sleep(1000); after the Send call, the receive application will read the data (at least when I tested it).


Most likely this is a bug in your code but without seeing the code it's impossible to tell.

However be aware that TCP/IP has no concept of messages, only a stream of data. So it's posisble to send 13 bytes and receive 6 in one read and 7 in the next. Or conversely to send 13 bytes then later send 7 more and on the receiveing side to receive them as a single block of 20 bytes.


Thank you so much for your interest. Here is the code:

/*********************************** Receiver **********************/

class Program { static void Main(string[] args) { Receiver recv = new Receiver(); recv.Start();
} }

public class Receiver
{
    public void Start()
    {
        Socket gateSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        gateSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8999));
        gateSocket.Listen(12);

        Thread thGateListen = new Thread(new ParameterizedThreadStart(GateListener));
        thGateListen.Start(gateSocket);
    }

    public void GateListener(object obj)
    {

        Socket gateSocket = (Socket)obj;

        for (; ; )
        {
            Socket newRequest = gateSocket.Accept();
            Console.WriteLine("New Connection Request");
            Thread thReadData = new Thread(new ParameterizedThreadStart(ReadFromSocket));
            thReadData.Start(newRequest);
        }
    }


    public void ReadFromSocket(object obj)
    {
        Socket s = (Socket)obj;
        for (; ; )
        {
            if (s.Available > 0)
            {
                byte[] buffer = new byte[s.Available];
                s.Receive(buffer);
                Console.WriteLine(System.Text.Encoding.ASCII.GetString(buffer));
            }
        }
    }

}

/*********************************** Sender **********************/

class Program { static void Main(string[] args) { Sender s = new Sender(); s.Send("Hello Socket!"); } }

class Sender
{
    public void Send(string s)
    {
        Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sendSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8999));

        sendSocket.Send(System.Text.Encoding.ASCII.GetBytes(s));
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜