The code is very simply divided into two classes, a server class and a client. During runtime, two threads are started, one is responsible for receiving and the other is responsible for sending.
The overall process is that two machines start the program separately, one chooses to actively connect and the other chooses to passively accept, which can achieve a QQ-like chat effect and two people can send messages at the same time.
Be careful, don’t start both on the same computer at the same time. This will cause the server and client IPs to be the same, which may cause the messages you send to be received by yourself. You can use two computers or virtual machines. Conducted inside the machine.
Server:
package com.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; import com.client.RunClient; public class RunServer { public static Socket socket=null; /** * 建立服务器被动连接 * @throws IOException */ public void startServer() throws IOException { //服务器接收数据 ServerSocket serverSocekt=new ServerSocket(8888); System.out.println("服务器启动,等待连接..."); //创建客户端线程 RunClient rc=new RunClient(); Thread rct=new Thread(rc); rct.start(); //阻塞线程 监听端口建立socket会话 RunServer.socket=serverSocekt.accept(); //获取输入留 InputStream is=socket.getInputStream(); //将字节输入流转换成字符输入流 InputStreamReader isr=new InputStreamReader(is); //将字符输入流装入带缓冲的输入流中 BufferedReader br=new BufferedReader(isr); String str=null; while((str=br.readLine())!=null){ System.out.print("输出信息:"+str); } socket.shutdownInput(); serverSocekt.close(); } }
Client:
package com.client; import java.io.BufferedWriter; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; import com.server.RunServer; public class RunClient implements Runnable { @Override public void run() { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); System.out.println("1、主动连接\n2、被动等待"); String sign=input.next(); switch (sign) { case "1": try { System.out.println("输入服务器IP:"); startClient(input.next()); } catch (Exception e) { e.printStackTrace(); } break; case "2": try { startClient(); } catch (Exception e) { e.printStackTrace(); } break; default: break; } } /** * 由已经建立的socket 进行连接反向连 * @throws Exception * @throws UnknownHostException */ public void startClient() throws Exception{ while(true){ try { if(RunServer.socket!=null){ break; } Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } // 与服务器建立连接 Socket socket=new Socket(RunServer.socket.getInetAddress().getHostAddress(), 8888); System.out.println("连接建立成功..."); //向服务器写入流 OutputStream os=socket.getOutputStream(); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os)); Scanner input=new Scanner(System.in); while(true){ System.out.println("输入信息:"); bw.write(input.next()); bw.newLine(); bw.flush(); } } /** * 通过IP与服务器建立连接 * @throws Exception * @throws UnknownHostException */ public void startClient(String ip) throws Exception{ // 与服务器建立连接 Socket socket=new Socket(ip, 8888); System.out.println("连接建立成功..."); //向服务器写入流 OutputStream os=socket.getOutputStream(); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os)); Scanner input=new Scanner(System.in); while(true){ bw.write(input.next()); bw.newLine(); bw.flush(); } } }
main:
package com.start; import com.server.RunServer; public class Go { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub RunServer rs=new RunServer(); rs.startServer(); } }
Effect: I use a virtual machine plus a local machine
The above is the detailed content of How to use java socket to implement LAN chat. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor