先看实现效果:
编辑
编辑
核心思想:
1使用socket建立连接
2客户端和服务器端分别创建两个进程,通过soccket来进行数据的发送和接收
话不多说,直接上代码
#客户端
package test; import java.io.*; import java.net.*; import java.util.*; public class TestClient { public static void main(String[] args) { try {//建立一个socket进行通信 Socket socket=new Socket("localhost",8001); System.out.println("开启客户端"); Thread thread1=new Thread(){//线程1重写run函数,用于接受数据 @Override public void run(){ try { InputStream i1=socket.getInputStream(); DataInputStream in1=new DataInputStream(i1); while(true)//建立封装输入流,随后用true不断读取数据 { String s1=in1.readUTF(); System.out.println("客户端:我收到的数据是:"+s1); } } catch (IOException e) { e.printStackTrace(); } } }; Thread thread2=new Thread() {//建立封装输出,随后使用true不断进行输出 @Override public void run(){ try { OutputStream o1=socket.getOutputStream(); DataOutputStream out1=new DataOutputStream(o1); Scanner sca1=new Scanner(System.in); while(true) { String s3=sca1.next(); out1.writeUTF(s3); } } catch (IOException e) { e.printStackTrace(); } } }; thread1.start(); thread2.start(); try { thread1.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("客户端关闭了"); socket.close(); } catch (IOException e) { System.out.println("断开连接"); e.printStackTrace(); } } }
#服务器端
package test; import java.io.*; import java.net.*; import java.util.*; public class TestServer { public static void main(String[] args) { //1建立连接 try { ServerSocket serverSocket = new ServerSocket(8001); System.out.println("开启服务端"); Socket s =serverSocket.accept();//等待建立连接 System.out.println("有连接过来了"+s); Thread thread1=new Thread(){//线程1收入数据 @Override public void run(){ try { InputStream i1=s.getInputStream(); DataInputStream in1=new DataInputStream(i1); while(true)//建立封装输入流,随后用true不断读取数据 { String s1=in1.readUTF(); System.out.println("服务端:我收到的数据是:"+s1); } } catch (IOException e) { e.printStackTrace(); } } }; Thread thread2=new Thread() {//建立封装输出,随后使用true不断输出 @Override public void run(){ try { OutputStream o1=s.getOutputStream(); DataOutputStream out1=new DataOutputStream(o1); Scanner sca1=new Scanner(System.in); while(true) { String s3=sca1.next(); out1.writeUTF(s3); } } catch (IOException e) { e.printStackTrace(); } } }; thread1.start(); thread2.start(); try { thread1.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("客户端关闭了"); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }