如何使用C#插槽连接两台独立的PC

时间:2019-06-17 12:04:46

标签: c# sockets ip

所以我有下面列出的用于服务器客户端通信的代码,只要您在同一台PC上启动两个程序,它就可以正常工作,但是,如果我尝试连接两个单独的PC,那是行不通的,有人知道我必须放在哪里在IP?我添加了一些Console.Writelines以获取带有注释的输出

        // ExecuteClient() Method 
        static void ExecuteClient(string message)
        {

            try
            {

                // Establish the remote endpoint  
                // for the socket. This example  
                // uses port 11111 on the local  
                // computer. 
                IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
                Console.WriteLine(ipHost); //System.Net.IPHostEntry
                IPAddress ipAddr = ipHost.AddressList[0];
                Console.WriteLine(ipHost.AddressList.ToString()); //System.Net.IPAddress[]
                Console.WriteLine(ipAddr); //gives back an ip v6 address
                IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
                Console.WriteLine(localEndPoint);
                // Creation TCP/IP Socket using  
                // Socket Class Costructor 
                Console.WriteLine("AddressFamily: " + ipAddr.AddressFamily.ToString()); //InterNetworkV6
                Socket sender = new Socket(ipAddr.AddressFamily,
                           SocketType.Stream, ProtocolType.Tcp);

                try
                {

                    // Connect Socket to the remote  
                    // endpoint using method Connect() 
                    sender.Connect(localEndPoint);

                    // We print EndPoint information  
                    // that we are connected 
                    Console.WriteLine("Socket connected to -> {0} ",
                                  sender.RemoteEndPoint.ToString());

                    // Creation of messagge that 
                    // we will send to Server 
                    byte[] messageSent = Encoding.ASCII.GetBytes("<EOF> " + message);
                    int byteSent = sender.Send(messageSent);

                    // Data buffer 
                    byte[] messageReceived = new byte[1024];

                    // We receive the messagge using  
                    // the method Receive(). This  
                    // method returns number of bytes 
                    // received, that we'll use to  
                    // convert them to string 
                    int byteRecv = sender.Receive(messageReceived);
                    Console.WriteLine("Message from Server -> {0}",
                          Encoding.ASCII.GetString(messageReceived,
                                                     0, byteRecv));

                    // Close Socket using  
                    // the method Close() 
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }

                // Manage of Socket's Exceptions 
                catch (ArgumentNullException ane)
                {

                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                }

                catch (SocketException se)
                {

                    Console.WriteLine("SocketException : {0}", se.ToString());
                }

                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
            }

            catch (Exception e)
            {

                Console.WriteLine(e.ToString());
            }
        }


//ExecuteServer method
        public static void ExecuteServer()
        {
            // Establish the local endpoint  
            // for the socket. Dns.GetHostName 
            // returns the name of the host  
            // running the application. 
            IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddr = ipHost.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);

            // Creation TCP/IP Socket using  
            // Socket Class Costructor 
            Socket listener = new Socket(ipAddr.AddressFamily,
                         SocketType.Stream, ProtocolType.Tcp);

            try
            {
                // Using Bind() method we associate a 
                // network address to the Server Socket 
                // All client that will connect to this  
                // Server Socket must know this network 
                // Address 
                listener.Bind(localEndPoint);

                // Using Listen() method we create  
                // the Client list that will want 
                // to connect to Server 
                listener.Listen(10);
                while (true)
                {

                    //Console.WriteLine("Waiting connection ... ");

                    // Suspend while waiting for 
                    // incoming connection Using  
                    // Accept() method the server  
                    // will accept connection of client 
                    Socket clientSocket = listener.Accept();

                    // Data buffer 
                    byte[] bytes = new Byte[1024];
                    string data = null;

                    while (true)
                    {

                        int numByte = clientSocket.Receive(bytes);

                        data += Encoding.ASCII.GetString(bytes,
                                                   0, numByte);

                        if (data.IndexOf("<EOF>") > -1)
                            break;
                    }

                    Console.WriteLine("Text received -> {0} ", data);
                    if(data == "<EOF> " + "kill")
                    {
                        Application.Exit();
                    } else if (data == "<EOF> " + "test")
                    {
                        Console.Writeline("It works!");
                    } else
                    {
                    byte[] message = Encoding.ASCII.GetBytes("Error 404 message not found!");
                    // Send a message to Client  
                    // using Send() method 
                    clientSocket.Send(message);
                        Messagebox1();
                    }
                    // Close client Socket using the 
                    // Close() method. After closing, 
                    // we can use the closed Socket  
                    // for a new Client Connection 
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                }
            }

            catch (Exception e)
            {
                //Console.WriteLine(e.ToString());
            }
        }

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.clientSocket.Connect(new IPEndPoint(System.Net.IPAddress.Parse(ip), int.Parse(port)));

并将IP地址传递到“ ip”变量。