下面的程序实现通过客户端向服务器端发送输入的消息,服务器端接收消息进行打印。
服务器端程序
package com.robert.view; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class ServerClient { ServerSocket server = null; Socket socket = null; InputStream inputStream = null; BufferedInputStream bis = null; DataInputStream dis = null; OutputStream outputStream = null; BufferedOutputStream bos = null; DataOutputStream dos = null; public static void main(String[] args) { ServerClient serverClient = new ServerClient(); serverClient.communicate(); } public void communicate() { try { server = new ServerSocket(9999); while (true) { socket = server.accept(); Runnable threadHandler = new ThreadHandler(socket); Thread thread = new Thread(threadHandler); thread.start(); } } catch (IOException e) { e.printStackTrace(); } } class ThreadHandler implements Runnable { private Socket socket; public ThreadHandler(Socket socket) { this.socket = socket; } @Override public void run() { try { String showInfo = ""; while (!"exit".equals(showInfo)) { inputStream = socket.getInputStream(); bis = new BufferedInputStream(inputStream); dis = new DataInputStream(bis); showInfo = dis.readUTF(); System.out.println(showInfo); } } catch (IOException e) { e.printStackTrace(); } } } }
客户端程序
package com.robert.view; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class CustomerClient { OutputStream outputStream = null; BufferedOutputStream bos = null; DataOutputStream dos = null; public static void main(String[] args) { CustomerClient customerClient = new CustomerClient(); customerClient.communication(); } public void communication() { try { Socket socket = new Socket("localhost", 9999); Runnable threadHandler = new ThreadHandler(socket); Thread thread = new Thread(threadHandler); thread.start(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } class ThreadHandler implements Runnable { Socket socket = null; public ThreadHandler(Socket socket) { this.socket = socket; } @Override public void run() { try { String input = ""; while (!"exit".equals(input)) { outputStream = socket.getOutputStream(); bos = new BufferedOutputStream(outputStream); dos = new DataOutputStream(bos); Scanner scanner = new Scanner(System.in); input = scanner.nextLine(); dos.writeUTF(input); dos.flush(); } } catch (IOException e) { e.printStackTrace(); } } } }