Client connection server (Java)

CSDN Q & A 2022-02-13 07:11:52 阅读数:711

client connection server java

This is the client code

package Client;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintStream;import java.net.Socket;import java.util.Scanner;public class client { private static final BufferedReader KEYBOARD_INPUT = new BufferedReader( new InputStreamReader(System.in)); public static String getString(String prompt) throws Exception { System.out.print(prompt); String str = KEYBOARD_INPUT.readLine(); return str; } public static void main(String args[]) throws Exception { Socket client = new Socket("47.96.154.95", 9999); Scanner scan = new Scanner(client.getInputStream()); scan.useDelimiter("\n"); PrintStream out = new PrintStream(client.getOutputStream()); boolean flag = true; while (flag) { String input = getString(" Please enter :").trim(); out.println(input); if (scan.hasNext()) { System.out.println(scan.next()); } if ("stop".equalsIgnoreCase(input)) { flag = false; } } scan.close(); out.close(); client.close(); }}

This is the code of the server ( Intranet IP:172.26.40.160, Public network IP:47.96.154.95; The firewall is open 9999 port )

package program_1;import java.io.IOException;import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;import java.util.Scanner;public class Server { public static class ClientThread implements Runnable { private Socket client = null; private Scanner scan = null; private PrintStream out = null; private boolean flag = true; public ClientThread(Socket client) throws Exception { this.client = client; this.scan = new Scanner(client.getInputStream()); this.scan.useDelimiter("\n"); this.out = new PrintStream(client.getOutputStream()); } @Override public void run() { while (this.flag) { if (scan.hasNext()) { String val = scan.next().trim(); if ("stop".equalsIgnoreCase(val)) { out.println("stoping..."); this.flag = false; } else { out.println("[ECHO]" + val); } } } try { scan.close(); out.close(); client.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String args[]) throws Exception { ServerSocket server = new ServerSocket(9999); System.out.println("wait for the client connect..."); boolean flag = true; while (flag) { Socket client = server.accept(); new Thread(new ClientThread(client)).start(); } server.close(); }}

When the client connects to the server , The client can't connect to the server , Why is that ???




Take the answer :

Check whether the server security group is open 9999 port



Other answers 2:

First use the network tool to check Interoperability . You start from the server Follow Client respectively telnet Next , have a look .

copyright:author[CSDN Q & A],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130711510661.html