search
HomeJavajavaTutorialImplementation process of socket programming in Java (code example)

The content of this article is about the implementation process of socket programming. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1.Socket server construction

Instantiate the socket server and obtain requests in a loop

package com.orange.util;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
 * socket服务器
 * 
 * @author Chengjq
 *
 */
public class SocketServer {
    public static int count = 0;
    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        int port = 4404;
        // 首先直接创建serversocket
        ServerSocket serverSocket = null;
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("启动socketServer成功,等待客户端的连接");
            while (true) {
                socket = serverSocket.accept();
                System.out.println("有新的客户端请求连接");
                SocketThread st = new SocketThread(socket);
                st.start();
                ChatManager.getChatManager().add(st);
                //启动定时任务,如果10s内没有进程
                /*Runnable runnable = new Runnable() {
                    int clientNum = 0;
                    public void run() {  
                        // task to run goes here  
                        clientNum = ChatManager.getChatManager().vector.size();
                        System.out.println("剩余客户端数量:"+clientNum);
                        if(clientNum ==0 ){
                            System.out.println("连接超时,或者无客户端连接,关闭serverSocket");
                            //关闭socket
                            //.....
                        }
                    }  
                };  
                ScheduledExecutorService service = Executors  
                        .newSingleThreadScheduledExecutor();  
                // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间  
                service.scheduleAtFixedRate(runnable, 2, 10, TimeUnit.SECONDS);  */
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            System.out.println("serverSocket已超时");
            try {
                socket.close();
                serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}

SocketThread class implements multi-threaded communication

package com.orange.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * SocketThread实现多线程通信
 * 
 * @author Administrator
 *
 */
public class SocketThread extends Thread {
	ServerSocket serverSocket = null;
	Socket socket = null;
	public SocketThread(ServerSocket serverSocket,Socket socket) {
		super();
		this.serverSocket = serverSocket;
		this.socket = socket;
	}
	public SocketThread(Socket socket) {
		super();
		this.socket = socket;
	}
	public void out(String out) {
        try {
            socket.getOutputStream().write(out.getBytes("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	public void publish(String out){
		ChatManager.getChatManager().publish(this, out);
	}
	

	@Override
	public void run() {
		// TODO Auto-generated method stub
		BufferedReader socketIn = null;
		PrintWriter socketOut = null;
		String inMess = null;
		try {
			socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			socketOut = new PrintWriter(socket.getOutputStream());
			while (true) {
				inMess = socketIn.readLine();
				publish(inMess);
				if("bye".equals(inMess)){
					ChatManager.getChatManager().remove(this);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				System.out.println("已结束当前会话");
				socketOut.close();
				socketIn.close();
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}

Single instance Chatmanage, for All client thread management and processing

package com.orange.util;
import java.util.Vector;
public class ChatManager {
    // 实现单例化
    private ChatManager() {
    };
    private static final ChatManager cm = new ChatManager();
    public static ChatManager getChatManager() {// 返回值为ChatManager
        return cm;
    }
    // 单例化完成
    Vector<SocketThread> vector = new Vector<SocketThread>();

    public void add(SocketThread st) {// 为当前集合添加SocketThread对象
        vector.add(st);
    }
    
    public void remove(SocketThread st) {// 当前客户端关闭连接
        vector.remove(st);
    }
    
    public void removeall() {// 关闭所有连接
        for (int i = 0; i < vector.size(); i++) {// 遍历所有的线程
            SocketThread csChatSocket = vector.get(i);
            if(csChatSocket!=null){
                vector.remove(csChatSocket);
            }
                
        }
    }

    // 某一个线程向其他的客户端发送信息
    public void publish(SocketThread st, String out) {
        for (int i = 0; i < vector.size(); i++) {// 遍历所有的线程
            SocketThread csChatSocket = vector.get(i);
            if (csChatSocket != st)// 判断不是当前线程就发送此消息
                csChatSocket.out(out + "\n");
        }
    }

    // 向当前线程发信息
    public void publish_present(SocketThread st, String out) {
        st.out(out + "\n");
    }
}

At this point, the server construction is completed

2. Client (create two clients)

Client 1 (listen to the specified server, through The console inputs messages for communication between the server and the client and between the clients,)

package com.orange;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 客户端1
 * @author Chengjq
 *
 */
public class SocketClient1 {

	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		try {
			//初始化客户端
			Socket socket = new Socket("127.0.0.1", 4404);
			BufferedReader readline = new BufferedReader(new InputStreamReader(System.in));
			//获取输出打印流
			PrintWriter socketOut = new PrintWriter(socket.getOutputStream());
			String outTemp = null;
			System.out.println("开始准备向服务器端发起请求---\n自己:");
			// 已启动连接socket服务器,准备实时接收来自其他客户端的消息
			GetMess getMess = new GetMess(socket);
			getMess.start();
			// 通过控制台发送消息给其他客户端,以“bye”为结束语
			while ((outTemp = readline.readLine()) != null) {
				//发送信息
				socketOut.println(outTemp);
				socketOut.flush();
				if("bye".equals(outTemp)){
					break;
				}
			}
			getMess.currentThread().interrupt();
			//依次关闭各种流
			readline.close();
			socketOut.close();
			socket.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

Client 2

package com.orange;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClient2 {
    @SuppressWarnings("static-access")
    public static void main(String[] args) {
        
        try {
            //初始化客户端
            Socket socket = new Socket("127.0.0.1", 4404);
            BufferedReader readline = new BufferedReader(new InputStreamReader(System.in));
            //获取输出打印流
            PrintWriter socketOut = new PrintWriter(socket.getOutputStream());
            String outTemp = null;
            System.out.println("开始准备向服务器端发起请求---\n自己:");
            // 已启动连接socket服务器,准备实时接收来自其他客户端的消息
            GetMess getMess = new GetMess(socket);
            getMess.start();
            // 通过控制台发送消息给其他客户端,以“bye”为结束语
            while ((outTemp = readline.readLine()) != null) {
                //发送信息
                socketOut.println(outTemp);
                socketOut.flush();
                if("bye".equals(outTemp)){
                    break;
                }
            }
            getMess.currentThread().interrupt();
            //依次关闭各种流
            readline.close();
            socketOut.close();
            socket.close();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        
    }
}

GetMess (multi-threaded processing to obtain messages from other clients and display them)

package com.orange;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class GetMess extends Thread {

    Socket socket = null;
    
    public GetMess(Socket socket) {
        super();
        this.socket = socket;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        BufferedReader socketIn = null;
        try {
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            socketIn = new BufferedReader(isr);
            String inTemp = null;
            while(true){
                inTemp = socketIn.readLine();
                if(inTemp != null && !"bye".equals(inTemp) ){
                    System.out.println("好友:\n"+inTemp);
                }else{
                    System.out.println("好友:\n已下线,关闭当前回话");
                    break;
                } 
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                Thread.currentThread().interrupt();
                socketIn.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        
    }

    
    
    
}

ok, the simple sockte service and client are completed

First start the server

and then start the client separately

##Enter bye to end the current session

The above is the detailed content of Implementation process of socket programming in Java (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function