套接字仅发送消息,无法从服务器接收消息

时间:2013-12-04 08:11:01

标签: c# sockets

我对我的套接字代码感到困惑,我希望从客户端收到消息,然后将其发送回客户端,但现在我只能从客户端收到消息,并且无法将其发回。那么如何更改代码才能实现呢?

这是我的服务器站点代码:

Socket MyClientSocket = (Socket)clientSocket;
while (true)
{
    try
    {
        int receiveNumber = MyClientSocket.Receive(result);
        message = Encoding.ASCII.GetString(result, 0, receiveNumber);
        Console.WriteLine("receive from{0}message{1}", 
            MyClientSocket.RemoteEndPoint.ToString(), message);
        MyClientSocket.Send(Encoding.ASCII.GetBytes(message));
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        MyClientSocket.Shutdown(SocketShutdown.Both);
        MyClientSocket.Close();
        break;
    }
}

客户端代码:

Main()
    {IPAddress ip = IPAddress.Parse("10.10.3.101");
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            clientSocket.Connect(new IPEndPoint(ip, 8885));
            Console.WriteLine("Connect success");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return;
        }
        int receiveLength = clientSocket.Receive(result);
        Console.WriteLine("Receive from server{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
        for (int i = 0; i < 10; i++)
        {
            try
            {
                Thread.Sleep(1000);
                string message = "client send message for help " + DateTime.Now;
                clientSocket.Send(Encoding.ASCII.GetBytes(message));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
        }
        Console.ReadLine();
    }
非常感谢。

0 个答案:

没有答案