服务器端代码(多线程):
import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class MultiEchoServer { private static ServerSocket serverSocket; private static final int PORT = 12345; public static void main(String[] args) throws IOException { try { serverSocket = new ServerSocket(PORT); } catch (IOException e) { System.out.println("Unable connect to the port"); System.exit(1); } do { Socket client = serverSocket.accept(); System.out.println("New client accept..."); ClientHandler clientHandler = new ClientHandler(client); clientHandler.start(); } while (true); } } class ClientHandler extends Thread { private Socket client; private Scanner input; private PrintWriter output; public ClientHandler(Socket client) { this.client = client; try { input = new Scanner(client.getInputStream()); output = new PrintWriter(client.getOutputStream(),true); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { String receive = ""; do { receive = input.nextLine(); System.out.println("Server receive message:" + receive); output.println("Echo:" + receive); } while (!receive.equalsIgnoreCase("q")); try { if (client != null) { System.out.println("Closing connection..."); client.close(); } } catch (IOException e) { System.out.println("Unable to close connection..."); } } }
客户端代码:
import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class MultiEchoClient { private static InetAddress host; private static final int PORT = 12345; public static void main(String[] args) { try { host = InetAddress.getLocalHost(); } catch (UnknownHostException e) { System.out.println("Host id not found!"); System.exit(1); } SenderMessages(); } public static void SenderMessages() { Socket socket = null; try { socket = new Socket(host, PORT); Scanner input = new Scanner(socket.getInputStream()); PrintWriter outpout = new PrintWriter(socket.getOutputStream(),true); Scanner userInput = new Scanner(System.in); String message, response; do { System.out.println("Enter Message:"); message = userInput.nextLine(); outpout.println(message); response = input.nextLine(); System.out.println("Server " + response); } while (!message.equalsIgnoreCase("q")); input.close(); userInput.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (socket != null) { System.out.println("Closing connetion..."); socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
时间: 2024-10-08 15:08:32