import java.io.*; import java.net.*; class Listen1 implements Runnable { Socket s; Listen1(Socket s) { this.s=s; } public void run() { while(true) { try { BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); String str=br.readLine(); System.out.println("Server Say:"); System.out.println(str); } catch (Exception e){} } } } class Write1 implements Runnable { Socket s; Write1(Socket s) { this.s=s; } public void run() { try { while(true) { PrintWriter out=new PrintWriter(s.getOutputStream(),true); BufferedReader br1=new BufferedReader(new InputStreamReader(System.in)); String str1=br1.readLine(); out.println(str1); } } catch(Exception e){} } } public class Client { public static void main(String[] args)throws Exception { Socket s=new Socket("172.16.99.99",12000); new Thread(new Listen1(s)).start();//读取信息线程 new Thread(new Write1(s)).start();//发送信息线程 } }
实现的一个聊天程序
最新推荐文章于 2020-01-13 17:28:46 发布
import java.io.*; import java.net.*; class Listen implements Runnable { Socket s; Listen(Socket s) { this.s=s; } public void run() { String ip=s.getInetAddress().getHostAddress(); while(true) { try { BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); String str=br.readLine(); System.out.println(ip+"Client Say:"); System.out.println(str); } catch (Exception e){} } } } class Write implements Runnable { Socket s; Write(Socket s) { this.s=s; } public void run() { try { while(true) { PrintWriter out=new PrintWriter(s.getOutputStream(),true); BufferedReader br1=new BufferedReader(new InputStreamReader(System.in)); String str1=br1.readLine(); out.println(str1); } } catch(Exception e){} } } public class Server { public static void main(String[] args)throws SocketException,IOException { ServerSocket sc=new ServerSocket(12000); Socket ss=sc.accept(); new Thread(new Listen(ss)).start(); new Thread(new Write(ss)).start(); } }