2013-04-20 180 views
0

我使服務器和客戶端之間的連接正常,我發送消息從客戶端到服務器,但我怎麼能發送消息從服務器到客戶端。我的意思是我怎麼能服務器的行爲就像一個客戶端too.i試圖將客戶端方法複製到另一個服務器可以調用的類。但我不能然後我試圖創建一個新的包來使用服務器class.any通知中的客戶端代碼?Java-udp編程 - 從服務器發送消息到客戶端

ps:對不起,我的英語。

public class Entrance_Server extends JFrame{ 

JButton buton = new JButton("Create"); 
JButton buton2 = new JButton("Join"); 
JPanel butonpanel = new JPanel(); 
DatagramSocket sockServer = null; 
DatagramSocket sockClient = null; 
int port = 7777; 
String s; 
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); 



public Entrance_Server() { 

    setLayout(new GridLayout(2,1)); 

    add(buton); 
    add(buton2); 

    buton.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 

      Choosing c = new Choosing(); 
      c.start(); 

      System.out.println("Server socket created. Waiting for incoming data..."); 



     } 
    }); 

    buton2.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      Choosing c = new Choosing(); 
      c.start(); 



     } 
    }); 

} 


public static void main(String[] args){ 

    Entrance_Server e = new Entrance_Server(); 
    e.setSize(500,350); 
    e.setTitle("Welcome"); 
    e.setLocationRelativeTo(null); 
    e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    e.setVisible(true); 

    e.connect(); 

} 

public void connect(){ 

     try{ 
       sockServer = new DatagramSocket(7777); 
       byte[] buffer = new byte[65536]; 
       DatagramPacket incoming = new DatagramPacket(buffer, buffer.length); 

       while(true) 
     { 
      sockServer.receive(incoming); 
      byte[] data = incoming.getData(); 
      String s = new String(data, 0, incoming.getLength()); 

      //echo the details of incoming data - client ip : client port - client message 
      System.out.println(incoming.getAddress().getHostAddress() + " : " + incoming.getPort() + " - " + s); 

      s = "OK : " + s; 
      DatagramPacket dp = new DatagramPacket(s.getBytes() , s.getBytes().length , incoming.getAddress() , incoming.getPort()); 
      sockServer.send(dp); 

      Entrance_Client_in_Server ec = new Entrance_Client_in_Server(); 
      ec.connectc(); 


     } 
      }catch(IOException i){ 
       System.err.println("IOException " + i); 
      } 



} 



} 

回答

2

在您的客戶端u需要使用socket.Receive()

您可以識別一個客戶,他有發送數據包到服務器就像你正在做後等待服務器的響應。然後,您可以indentify客戶端這樣的: InetAddress address = packet.getAddress(); int port = packet.getPort();

並用它來發送一個數據包發送回客戶端,這將讀取使用socket.Receive()的響應;

對於使用UDP DatagramSockets有關客戶端/服務器連接的詳細信息檢查 Client-Server Datagram sockets

+0

它的工作是非常簡單的solution.thank你這麼多。 – theduman 2013-04-20 16:00:33

相關問題