效果:
服务端
客户端
实现代码:
服务端
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class SocketServer { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8888); System.out.println("群聊聊天室开启..."); //定义初始上线人数为0 int i=0; while (true) { Socket socket = server.accept(); i++; System.out.println("上线通知:"+socket.getInetAddress()+":"+socket.getPort()); //读(使用多线程实现读的功能) new Thread(new ServerThread(socket)).start(); System.out.println("目前上线人数"+i+"人"); } } }
线程类
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; public class ServerThread implements Runnable{ public Socket socket; public ServerThread(Socket socket) { super(); this.socket = socket; } @Override public void run() { // TODO Auto-generated method stub try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); while (true) { String readLine = bufferedReader.readLine(); System.out.println(readLine); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
客户端
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class SocketClient { public static void main(String[] args) throws UnknownHostException, IOException { Socket socket = new Socket("127.0.0.1",8888); System.out.println("您好吕布,您已经上线了"); //构建从控制台输入的输入流 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //构建从客户端输出的输出流 PrintWriter pw=new PrintWriter(socket.getOutputStream()); while (true) { pw.println("吕布说:"+br.readLine()); pw.flush(); } } }