During execution, the server starts with java test 1 and the client starts with java test. When the server type A character, the client prints the corresponding character, I hope the following code will be useful to you.
- Import java.net .*;
- Public class test {
- Public static int serverPort = 666;
- 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:
- 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 {
- // TODO Auto-generated method stub
- If (args. length = 1 ){
- Ds = new DatagramSocket (serverPort );
- TheServer ();
- } Else {
- Ds = new DatagramSocket (clientPort );
- TheClient ();
- }
- }
- }