欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java网络编程实现多客户端连接服务器

程序员文章站 2024-03-23 09:39:58
...

使用多线程实现多客户端连接服务器,

客户端代码如下:

/**
 * Socket客户端
 * 功能为:发送字符串nihao到服务器端,并打印出服务器端的返回信息
 */
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketClient {

	public static void main(String[] args) {
		Socket socket = null;
		InputStream is = null;
		OutputStream os = null;
		// 服务器IP
		String serverIP = "127.0.0.1";
		// 服务器端口
		int port = 8080;
		try {
			// 建立连接
			socket = new Socket(serverIP, port);
			is = socket.getInputStream();
			os = socket.getOutputStream();
			//发送信息
			os.write("nihao".getBytes());
			//接收信息
			byte[] buffer = new byte[1024]; 
			int n = is.read(buffer);
			// 输出返回信息
			System.out.println("接收服务器信息:" + new String(buffer, 0, n));
		} catch (Exception e) {
			e.printStackTrace(); 
		} finally {
			try {
				//关闭流和连接
				is.close();
				os.close();
				socket.close();
			} catch (Exception e2) {
			}
		}
	}
}

服务器端代码如下:

 

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
public class SocketServer {

	public class ClientHandler implements Runnable {
 
		Socket socket = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;

		public ClientHandler(Socket socket) {
			this.socket = socket; 
		}

		public void run() {
			byte[] buffer = new byte[1024];
			//读取数据
            int length;
			try {
				inputStream = socket.getInputStream();
				outputStream = socket.getOutputStream();
				length = inputStream.read(buffer); 
	            System.out.println(new String(buffer,0,length)); 
	            outputStream.write("niyehao".getBytes());
			} catch (IOException e) {
 				e.printStackTrace(); 
			}finally{
				try {
					inputStream.close();
					outputStream.close();
					socket.close();
				} catch (IOException e) { 
 					e.printStackTrace();
				}
			}
		} 
	}
	
	public static void main(String[] args){
		new SocketServer().StartServer();  
 
	}
	
	public void StartServer(){
		ServerSocket serverSocket  = null;
		Socket socket = null;
		int port=5555;
		try{
			serverSocket = new ServerSocket(port);
			System.out.println("server start");
			while(true){
				socket = serverSocket.accept(); 
				System.out.println("client connectioned,IP:"+socket.getInetAddress()); 
				Thread t = new Thread(new ClientHandler(socket));
                t.start();
			}
		}catch(IOException e){
			e.printStackTrace();
		} finally{
			 
		}
	}
}