public class ServerThread extends Thread{ Socket socket = null; public ServerThread(Socket socket) { this.socket = socket; } @Override public void run() { // TODO Auto-generated method stub try { InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String info = null; while ((info=br.readLine())!=null) { System.out.println("我是服务器,客户端说" + info); } socket.shutdownInput(); OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("欢迎您"); pw.flush(); pw.close(); os.close(); br.close(); isr.close(); is.close(); socket.close(); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } } }
public class Client { public static void main(String[] args) { try { Socket socket = new Socket("localhost",8888); OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("用户名:tom;密码:123"); pw.flush(); socket.shutdownOutput(); InputStream is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String info = null; while ((info=br.readLine())!=null) { System.out.println("我是客户端,服务器说" + info); } br.close(); is.close(); pw.close(); os.close(); socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public class Server { public static void main(String[] args) { int count =0; try { ServerSocket serverSocket = new ServerSocket(8888); System.out.println("服务器即将启动,等待客户端的连接"); Socket socket = null; while (true) { count++; socket = serverSocket.accept(); ServerThread serverThread = new ServerThread(socket); serverThread.start(); System.out.println(count); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
原文:https://www.cnblogs.com/dulute/p/10824837.html