Run application both as server and client

无人久伴 提交于 2019-12-04 12:04:37

Currently your application will either run as the server or the client, depending on whether or not you provide a command line argument. To run as both within the same process, you'd want to start two threads (at least) - one for the server and one for the client.

For the moment though, I'd just start it up twice in two different command windows - once with a command line argument (to make it the client) and once without (to make it the server).

EDIT: I've just noticed that your main method will never run Server(). So you need to change it to something like this:

if (args.length == 1) {
  Client();
} else {
  Server();
}

(You might also want to start following Java naming conventions at the same time, by the way, renaming the methods to client() and server().)

Then remove the Server() call from the end of Client(), and call the parameterless DatagramSocket constructor in Client() to avoid trying to be a server...

The finished code might look something like this:

import java.io.IOException;
import java.net.*;

public class ClientServer {

   private static void runClient() throws IOException {
     InetAddress address = InetAddress.getLocalHost();
     DatagramSocket ds=new DatagramSocket();
     int pos = 0;
     byte[] buffer = new byte[100];
     while (pos < buffer.length) {
       int c = System.in.read();
       buffer[pos++]=(byte)c;
       if ((char)c == '\n') {
         break;
       }
     }
     System.out.println("Sending " + pos + " bytes");
     ds.send(new DatagramPacket(buffer, pos, address, 3000));
  }                   

  private static void runServer() throws IOException {
    byte[] buffer = new byte[100];
    InetAddress address = InetAddress.getLocalHost();
    DatagramSocket ds = new DatagramSocket(3000, address);
    DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
    ds.receive(dp);
    System.out.print(new String(dp.getData(), 0, dp.getLength()));
  }

  public static void main(String args[]) throws IOException {
    if (args.length == 1) {
      runClient();
    } else {
      runServer();
    }
  }
}

Note that this still isn't great code, in particular using the system default string encoding... but it works. Start the server in one window by running java ClientServer, then in another window run java ClientServer xxx, type a message and press return. You should see it in the server window.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!