运行应用程序作为服务器和客户端
我想让我的电脑兼顾服务器和客户端。 这是我的代码
import java.net.*; class tester { static int pos=0; static byte buffer[]=new byte[100]; static void Client() throws Exception { InetAddress address=InetAddress.getLocalHost(); DatagramSocket ds=new DatagramSocket(3000,address); while(true) { int c=System.in.read(); buffer[pos++]=(byte)c; if((char)c=='\n') break; } ds.send(new DatagramPacket(buffer,pos,address,3000)); Server(); } static void Server() throws Exception { InetAddress address=InetAddress.getLocalHost(); DatagramSocket ds=new DatagramSocket(3001,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 Exception { if(args.length==1) { Client(); } }
}
在这方面,我试图让我的电脑兼顾服务器和客户端。 我在cmd上运行这个程序作为java tester hello
但程序一直在等待。 我应该怎么做以接收键入的消息。
*如果代码中有任何修改,请提出建议。 请注意,目的是使我的电脑和服务器兼容。
目前,您的应用程序将作为服务器或客户端运行,具体取决于您是否提供命令行参数。 要在同一个进程中运行,您需要启动两个线程(至少) – 一个用于服务器,一个用于客户端。
暂时,我只是在两个不同的命令窗口中启动两次 – 一次使用命令行参数(使其成为客户端),一次不启动(使其成为服务器)。
编辑:我刚刚注意到你的main方法永远不会运行Server()
。 所以你需要把它改成这样的东西:
if (args.length == 1) { Client(); } else { Server(); }
(您可能还希望同时开始遵循Java命名约定,顺便说一下,将方法重命名为client()
和server()
。)
然后从Client()
的末尾删除Server()
调用,并在Client()
调用无参数的DatagramSocket
构造函数,以避免尝试成为服务器…
完成的代码可能如下所示:
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(); } } }
请注意,这仍然不是很好的代码,特别是使用系统默认字符串编码...但它的工作原理。 通过运行java ClientServer
在一个窗口中启动服务器,然后在另一个窗口中运行java ClientServer xxx
,键入消息并按回车键。 您应该在服务器窗口中看到它。