socket ( java ) 簡單多個用戶端、服務端通訊(多線程)

來源:互聯網
上載者:User
原創作品,允許轉載,轉載時請務必以超連結形式標明文章 原始出處 、作者資訊和本聲明。否則將追究法律責任。http://blog.csdn.net/love254443233/article/details/7897269


實現:

用戶端:多個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();}}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.