局域网内实现单客户端与服务器通信

客户端通过配置ip和端口号来连接服务器

客户端和服务器端各自具有发送和接收线程,可以实现一方持续发送

服务器端
package Net; import java.io.IOException; import java.net.ServerSocket; import
java.net.Socket; public class Server2 { public static void main(String[] args)
throws IOException { ServerSocket serverSocket=new ServerSocket(9999);
System.out.println("服务器已启动等待连接"); Socket socket=serverSocket.accept();
System.out.println("连接成功"); In in=new In(socket,"张三"); Out out=new Out(socket);
in.start(); out.start(); } }
客户端
package Net; import java.io.IOException; import java.net.Socket; public class
Client2 { public static void main(String[] args) throws IOException { Socket
socket=new Socket("127.0.0.1",9999); if(socket.isConnected()){
System.out.println("连接成功"); } In in=new In(socket,"张修"); Out out=new
Out(socket); in.start(); out.start(); } }
输入线程
package Net; import java.io.DataInputStream; import java.io.IOException;
import java.io.InputStream; import java.net.ServerSocket; import
java.net.Socket; public class In extends Thread{ Socket socket; String name;
public In(Socket socket){ this.socket=socket; } public In(Socket socket,String
name){ this.socket=socket; this.name=name; } @Override public void run() {
InputStream inputStream= null; try { inputStream = socket.getInputStream(); }
catch (IOException e) { e.printStackTrace(); } DataInputStream din=new
DataInputStream(inputStream); while(true){ try { String ss=din.readUTF();
System.out.println(name+":"+ss); } catch (IOException e) { e.printStackTrace();
} } } }
输出线程
package Net; import java.io.*; import java.net.ServerSocket; import
java.net.Socket; import java.util.Scanner; public class Out extends Thread{
Socket socket; String name; public Out(Socket socket){ this.socket=socket; }
@Override public void run() { OutputStream out = null; try { out =
socket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); }
DataOutputStream dout = new DataOutputStream(out); Scanner scanner=new
Scanner(System.in); while(true){ String s= scanner.next(); try {
dout.writeUTF(s); } catch (IOException e) { e.printStackTrace(); } } } }
测试

开启服务器端

开启客户端

开始聊天

 

 

 

 

 

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:766591547
关注微信