2011-03-23 133 views
0

我寫了一個客戶端服務器程序:使單個客戶端和服務器

{ 
    import java.net.*; 
    class verify { 
    public static int serverPort=998; 
    public static int clientPort=999; 
    public static int buffer_size=1024; 
    public static DatagramSocket ds; 
    public static byte buffer[]=new byte[buffer_size]; 

    public static void TheServer() throws Exception { 
    int pos=0; 
    while (true) { 
    int c=System.in.read(); 
    switch(c) { 
     case -1: 
      System.out.println("server quits"); 
      return; 
     case '\r': 
      break; 
     case '\n': 
      ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort)) ; 
      pos=0; 
      break; 
     default: 
      buffer[pos++] = (byte) c; 
    } 
    } 
    } 

public static void TheClient()throws Exception { 
    while(true) { 
    DatagramPacket p=new DatagramPacket(buffer,buffer.length); 
    ds.receive(p); 
    System.out.println(new String(p.getData(),0,p.getLength())); 
    } 
} 

public static void main(String args[]) throws Exception{ 
    if(args.length==1) { 
    ds=new DatagramSocket(serverPort); 
    TheServer(); 
    } else { 
    ds=new DatagramSocket(clientPort); 
    TheClient(); 
    } 
    } 
} 
} 

我可以讓我的PC服務器和client.If既肯定請出建議的方式。

+0

請使用代碼格式功能。您帖子中的代碼很難閱讀。 – Mudassir 2011-03-23 05:56:49

+0

@ Mudassir改進了代碼 – 2011-03-23 06:10:23

回答

1

是的,你的電腦絕對可以是服務器和客戶端。但是,如何從你的代碼中獲得這些信息我不能說。

一般來說,在TheServer()中,您需要創建一個ServerSocket並將其設置爲在serverPort上進行收聽。然後執行諸如Socket clientSocket = serverSocket.accept()之類的操作來等待並接受下一個傳入連接。

然後在TheClient()中,您將創建一個新的SocketserverPort上的「localhost」。這將連接你的服務器和客戶端。

請注意,因爲serverSocket.accept()塊,您的服務器和客戶端不能共享線程。因此,您可以像現在一樣運行兩個單獨的應用程序實例,也可以使用main()TheServer()設置一個新線程,然後在撥打TheClient()之前啓動它。

+0

改進了代碼 – 2011-03-23 06:09:41

+0

@Suhail - 謝謝,這樣更具可讀性。爲什麼你使用'DatagramSocket'而不是'ServerSocket'和'Socket'有什麼特別的理由? – aroth 2011-03-23 06:13:15

+0

不,沒有任何特別的原因。我只是想通過消息 – 2011-03-23 06:19:01

0

只要客戶端和服務器在不同的端口上發送和接收,那麼就沒有理由讓客戶端和服務器都不在同一臺機器上運行。事實上,在我測試客戶端/服務器應用程序時,我在大學期間經常這樣做。

+0

使端口號相同的工作? – 2011-03-23 06:24:45

+0

@Suhail Gupta - 不,不同。因此,例如,使用3000作爲服務器發送,3001作爲服務器監聽,3002作爲客戶端發送,3003作爲客戶端監聽。 – 2011-03-23 06:32:22