-3

我想要 C# 客户端和 Java 服务器中的聊天应用程序

我通过 C# 客户端,但是当我响应 Java 服务器时出现了一些错误,我得到了错误@

无法访问已处置的对象 object name='System.Net.Socket.Socket'

class Program
{
    static void Main(string[] args)
    {
        byte[] bytes = new byte[1024];// data buffer for incoming data

        // connect to a Remote device
        try
        {
            // Establish the remote end point for the socket
            IPHostEntry ipHost = Dns.Resolve("localhost");
           IPAddress ipAddr = ipHost.AddressList[0];
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 95);
            Socket Socketsender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // Connect the socket to the remote endpoint
            Socketsender.Connect(ipEndPoint);

            Console.WriteLine("\n\n___________________Client Server Chat Application__________________________");
            Console.WriteLine("___________________________________________________________________________");
            Console.WriteLine("\nSocket Connecting To Java Server...." + Socketsender.RemoteEndPoint.ToString());
           // Console.ReadLine();
            string data = null;

            while (true) 
            {
                //Recieved from Java Server Message
                int bytesRec = Socketsender.Receive(bytes);
                Console.WriteLine("\nJava Server:: {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
              //  Console.ReadLine();

                    Console.Write("C# Client  ::"); // Prompt
                    string line = Console.ReadLine();

                    byte[] sendToServer = Encoding.ASCII.GetBytes(line);
                    // Send the data through the socket
                    int intByteSend = Socketsender.Send(sendToServer);
               //  Socketsender.Shutdown(SocketShutdown.Both);

                Socketsender.Close();
                               Console.WriteLine("____________________________________________________________________________");
                Console.WriteLine("_________________________End Chat___________________________________________");                  
                // Socketsender.Shutdown(SocketShutdown.Both);
              Socketsender.Close();

            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        Console.ReadLine();
    }


}
4

1 回答 1

5

你正在他的 while 循环中关闭你的套接字 ( Socketsender),然后——在下一次迭代中——调用Receive它。

一旦套接字关闭,它就死了,1并且不能用于任何事情。您需要创建一个新套接字并将其连接到服务器。

或者更好的是,保持第一个套接字打开。

(您也执行了两次关闭,但我假设这是一个转录错误。)


1在此处插入死鹦鹉。

于 2013-08-24T09:58:30.880 回答