2017-03-01 60 views
-2

我試圖將客戶端連接到不同網絡上的服務器(通過Internet),我朋友的PC上的客戶端和使用TCP的服務器上的客戶端,但是我在客戶端中獲取無效IP。 IP是硬編碼,只是爲了測試連接和發送東西的能力。使用TCP連接不同網絡上的客戶端和服務器

客戶端代碼:

class Client 
{ 
    Socket clientSocket; 
    byte[] buffer; 

    public Client() 
    { 
     initializeClient(); 
    } 

    private void initializeClient() 
    { 
     clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     buffer = Encoding.ASCII.GetBytes("hi server, i am a client"); 
     clientSocket.Connect(new IPAddress(Encoding.ASCII.GetBytes("156.205.***.**")), 100); 
     //***.** altered by me to protect my IP but the ip is written complete in the code 
     clientSocket.Send(buffer); 
     clientSocket.Close(); 
    } 
} 

Server代碼:

class Server 
{ 
    static byte[] buffer; 
    static Socket serverSocket; 
    static List<Socket> clientSockets; 

    private void initializeServer() 
    { 
     serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     clientSockets = new List<Socket>(); 
     buffer = new byte[1024]; 
     serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100)); 
     serverSocket.Listen(5); 
     while (true) 
     { 
      Socket newClient = serverSocket.Accept(); 
      Console.WriteLine("new Client accepted: "+ newClient.RemoteEndPoint.ToString()); 
      Thread newThread = new Thread(new ParameterizedThreadStart(AcceptClients)); 
      newThread.Start(newClient); 
     } 
    } 

    public Server() 
    { 
     initializeServer(); 
    } 

    private void AcceptClients(object obj) 
    { 
     Socket client = (Socket)obj; 
     clientSockets.Add(client); 
     int recevied = client.Receive(buffer); 
     Console.WriteLine("client said: " + Encoding.ASCII.GetString(buffer, 0, recevied)); 
     client.Close(); 
    } 
} 
+0

_「但我在客戶端中獲取無效的IP」_ - 請閱讀[問]並張貼實際的異常消息,包括您的研究。有可能你沒有轉發合適的端口。網絡上詳細記錄瞭如何做端口轉發。 – CodeCaster

+0

@CodeCaster我做了端口轉發,使我的IP靜態,然後將端口100添加到我的路由器虛擬服務器,但仍然收到相同的錯誤:未處理的異常:System.ArgumentException:指定了一個無效的IP地址。 參數名稱:地址 在System.Net.IPAddress..ctor(Byte []地址) –

+1

哦,是的,編碼.ASCII.GetBytes(「156.205。***。**」)不會工作。你可能需要'new byte [] {156,205,...}'或者簡單地調用'IPAddress.Parse(「156.205 ....」)''。 – CodeCaster

回答

1

Encoding.ASCII.GetBytes( 「156.205 *」)是錯誤的。它與新的字節[] {156,205,...}

相關問題