1. 程式人生 > >socket ( java ) 簡單多個客戶端、服務端通訊(多執行緒)

socket ( java ) 簡單多個客戶端、服務端通訊(多執行緒)

實現:

客戶端:多個socket(多個埠),其中一個客戶端的一個埠用於接收服務端傳送過來的訊息,其一個用於向服務端傳送訊息。其它客戶端只有發訊息的功能。

服務端:兩個socket,一個用於迴圈接收客戶端傳送過來的socket請求。一個用於接收訊息手自動向客戶端傳送訊息。

注:先執行MySocketServer,然後MySocketClient,最後SocketClient;MySocketClient、SocketClient向MySocketServer傳送訊息。

1、MySocketServer類:

package socket._5;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MySocketServer {
	private static int localHostPort = 5000;

	public static void main(String[] args) throws IOException {
		ServerSocket s = new ServerSocket(localHostPort);
		System.out.println("伺服器端------監聽中.....");
		while (true) {
			Socket socket = s.accept();
			System.out.println("接入的socket:" + socket);
			GetMessage getMessage = new GetMessage(socket);
			Thread thread = new Thread(getMessage);
			thread.start();
		}
	}
}

// 接收訊息
class GetMessage implements Runnable {
	private int remotePort = 5001;
	private String remoetAddress = "localhost";
	private InputStream inputStream;
	private OutputStream outputStream;
	private Socket socketGet;
	private Socket socketSendMessage;
	private boolean socketIsExits = false;
	private int sum = 0;

	private byte[] buffer;

	public GetMessage(Socket socket) {
		this.socketGet = socket;
		try {
			inputStream = socketGet.getInputStream();
			outputStream = socketGet.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		String str = "";
		int n = 0;
		while (true) {
			try {
				buffer = new byte[2048];
				n = inputStream.read(buffer);
				str = new String(buffer, 0, n);
				System.out.print("客戶端:" + str);
				sendMessage();
			} catch (IOException e) {
				e.printStackTrace();
				break;
			}
			if (str.equals("q")) {
				break;
			}
		}
		try {
			if (socketGet != null)
				socketGet.close();
			if (inputStream != null)
				inputStream.close();
		} catch (Exception e) {

		}
	}

	// 傳送訊息
	public void sendMessage() throws IOException {
		if (socketIsExits) {
			try {
				String input = "======" + (sum++);
				System.out.println("服務端傳送 socket:" + this.socketSendMessage);
				outputStream.write(input.getBytes());
				System.out.println("伺服器:" + input);
				outputStream.flush();
			} catch (Exception e) {
				System.out.println("客戶端socket不存在。");
				checkSocket();
			}
		} else {
			checkSocket();
		}
	}

	private void checkSocket() {
		try {
			socketSendMessage = new Socket(remoetAddress, remotePort);
			outputStream = socketSendMessage.getOutputStream();
			socketIsExits = true;
		} catch (Exception e) {
			socketIsExits = false;
		}
	}
}

2、MySocketClient類:

package socket._5;

import java.io.*;
import java.net.*;

public class MySocketClient {
	private static int localHostPort = 5001;

	public static void main(String[] args) throws IOException {

		CSendMessage cSendMessage = new CSendMessage();
		Thread thread2 = new Thread(cSendMessage);
		thread2.start();

		ServerSocket serverSocket = new ServerSocket(localHostPort);
		while (true) {
			Socket socketServer = serverSocket.accept();
			CGetMessage getMessage = new CGetMessage(socketServer);
			Thread thread = new Thread(getMessage);
			thread.start();
		}
	}
}

// 接收訊息
class CGetMessage implements Runnable {
	private InputStream inputStream;
	private Socket socket;
	private byte[] buffer;

	public CGetMessage(Socket socket) {
		this.socket = socket;
		try {
			inputStream = socket.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		String str = "";
		while (true) {
			buffer = new byte[2048];
			int n = 0;
			try {
				n = inputStream.read(buffer);
				str = new String(buffer, 0, n);
				System.out.println("伺服器:" + str);
			} catch (IOException e) {
				e.printStackTrace();
				break;
			}
			if (str.equals("q")) {
				break;
			}
		}
		try {
			if (socket != null)
				socket.close();
			if (inputStream != null)
				inputStream.close();
		} catch (Exception e) {

		}
	}
}

// 傳送訊息
class CSendMessage implements Runnable {
	private boolean socketIsExits = false;
	private OutputStream outputStream;
	private Socket socketClient;
	private int remotePort = 5000;
	private String remoteAddress = "localhost";
	private byte[] buffer;

	public CSendMessage() throws IOException {
	}

	public void run() {
		String str = new String();
		checkSocket();
		int size = 0;
		while (true) {
			try {
				System.out.println("請輸入:");
				buffer = new byte[2048];
				size = System.in.read(buffer);
				str = new String(buffer, 0, size);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (socketIsExits) {
				try {
					System.out.println("客戶端傳送 socket:" + this.socketClient);
					System.out.print("客戶端:" + str);
					outputStream.write(str.getBytes());
					outputStream.flush();
				} catch (Exception e) {
					System.out.println("客戶端socket不存在。");
					checkSocket();
				}
			} else {
				checkSocket();
			}
		}
	}

	private void checkSocket() {
		try {
			socketClient = new Socket(remoteAddress, remotePort);
			outputStream = socketClient.getOutputStream();
			socketIsExits = true;
		} catch (Exception e) {
			socketIsExits = false;
		}
	}
}

3、SocketClient類:

package socket._5;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClient implements Runnable {
	public int remotePort = 5000;
	public String remoteAddress = "localhost";
	
	
	public static void main(String args[]) {
		SocketClient socketClient = new SocketClient();
		socketClient.run();
	}
	

	public SocketClient() {
	}	
	
	public void run() {
		Socket socket = null;
		OutputStream outputStream = null;
		byte[] buffer;
		int size = 0;		
		try {
			socket = new Socket(remoteAddress, remotePort);
			outputStream = socket.getOutputStream();
			System.out.println(socket);			
			while (true) {
				System.out.println("input:");
				buffer = new byte[2048];
				size = System.in.read(buffer);
				if (size > 0) {
					outputStream.write(new String(buffer, 0, size).getBytes());
					outputStream.flush();
				}
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (socket != null)
					socket.close();
				if (outputStream != null)
					outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}

溝通交流請關注公眾號。