Home >Java >javaTutorial >How to use java socket to implement LAN chat

How to use java socket to implement LAN chat

WBOY
WBOYforward
2023-04-18 23:25:011700browse

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

How to use java socket to implement LAN chat

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete