我在java服务器和客户端创建了两个程序,我通过localhost连接,但我想通过互联网连接全世界的客户端。
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 1234);
OutputStream outputStream = socket.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeInt(Integer.parseInt(args[0]));
InputStream inputStream = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(inputStream);
System.out.println(dataInputStream.readUTF());
}
}
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(1234);
while(true) {
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(inputStream);
int a = dataInputStream.readInt();
OutputStream outputStream = socket.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
if(a == 1698)
dataOutputStream.writeUTF("Welcome Salman");
else if(a == 1700)
dataOutputStream.writeUTF("Welcome Wajeh");
else if(a == 1694)
dataOutputStream.writeUTF("Welcome Farhan");
else
dataOutputStream.writeUTF("Wrong Roll No");
}
}
}
答案 0 :(得分:0)
与浏览器连接到SO的方式相同,您应该获取服务器的IP地址并连接到它,这可以通过DNS完成。
答案 1 :(得分:0)
您可以通过替换该行的参数来执行此操作:
Socket socket = new Socket("localhost", 1234);
进入服务器的公共IP地址和运行应用程序的端口。