运用TCP编程,实现一个从客户端到服务端多线程聊天的功能。
获取信息线程的代码
Get.java
package com.xyq.HW; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; public class Get extends Thread{ private Socket socket; Get(Socket socket){ this.socket = socket; }
@Override public void run() { while(true){ try { InputStream is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String content = br.readLine(); System.out.println("发送的内容是"+content); } catch (Exception e) { e.printStackTrace(); } } } }
发送信息线程的代码
Send.java
package com.xyq.HW; import java.io.*; import java.net.Socket; import java.util.Scanner; public class Send extends Thread{ Scanner sc = new Scanner(System.in); private Socket socket; Send(Socket socket){ this.socket = socket; } @Override public void run() { while(true){ try { OutputStream os = socket.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); String content = sc.nextLine(); bw.write(content); bw.newLine(); bw.flush(); } catch (Exception e) { e.printStackTrace(); } } }
客户端代码Client.java
package com.xyq.HW; import java.net.Socket; public class Client { public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost",9999); Get rt = new Get(socket); rt.start(); //4.启动第二个线程 Send st = new Send(socket); st.start(); } }
服务器代码Server.java
package com.xyq.HW; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[]args) throws IOException { //1.创建连接 ServerSocket ss = new ServerSocket(9999); //2.等待客户端连接 Socket socket = ss.accept(); //3.客户端连接后启动第一个线程 Get rt = new Get(socket); rt.start(); //4.启动第二个线程 Send st = new Send(socket); st.start(); } }
实现效果:
标签:java,socket,编程,TCP,import,new,多线程,public,Socket From: https://www.cnblogs.com/sxwgzx23/p/17726510.html