2013-04-20 139 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

相关问题