亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術(shù)文章
文章詳情頁

具有多客戶端通信的Java Server。

瀏覽:72日期:2024-04-24 10:22:21
如何解決具有多客戶端通信的Java Server。?

在這里,我與您分享了一個不錯的 ,其中包含一臺服務(wù)器,該服務(wù)器根據(jù)您的要求使用TCP協(xié)議與多個客戶端進行通信。

程序包含:

@H_403_5@無論在何處添加新客戶,都會通知每個客戶及其名稱和職位。@H_403_5@它還會檢查現(xiàn)有名稱。程序不允許多個客戶端使用相同的名稱。

使用此程序作為游戲的初始啟動器。如果您想在程序中添加新功能,請告訴我。

這是代碼(有關(guān)更多說明,請參見代碼注釋):

在端口號1234上運行此程序之前,請先替換LiveChatClient.java文件中的主機名。

運行程序的步驟:

@H_403_5@第一次只運行LiveChatServer@H_403_5@然后為要添加的多個客戶端運行LiveChatClient

用于設(shè)置客戶端-服務(wù)器通信協(xié)議的操作代碼

package com.chat;/**************** an interface to define different operation code **************/public interface Opcode { int CLIENT_CONNECTEING = 1; int CLIENT_CONNECTED = 2;}

控制多個客戶端的單個服務(wù)器

package com.chat;/************************ Live Chat Server *******************/import java.io.IOException;import java.net.InetAddress;import java.net.ServerSocket;import java.net.socket;import java.util.HashMap;import java.util.LinkedHashMap;public class LiveChatServer { // Connection state info private static LinkedHashMap<String, ClientThread> clientInfo = new LinkedHashMap<String, ClientThread>(); // TCP Components private ServerSocket serverSocket; // Main Constructor public LiveChatServer() {startServer();// start the server } public void startServer() {String port = '1234';try { // in constractor we are passing port no, back log and bind address whick will be local // host // port no - the specified port, or 0 to use any free port. // backlog - the maximum length of the queue. use default if it is equal or less than 0 // bindAddr - the local InetAddress the server will bind to int portNo = Integer.valueOf(port); serverSocket = new ServerSocket(portNo, 0, InetAddress.getLocalHost()); System.out.println(serverSocket); System.out.println(serverSocket.getInetAddress().getHostName() + ':' + serverSocket.getLocalPort()); while (true) {Socket socket = serverSocket.accept();new ClientThread(socket); }} catch (IOException e) { System.out.println('IO Exception:' + e); System.exit(1);} catch (NumberFormatException e) { System.out.println('Number Format Exception:' + e); System.exit(1);} } public static HashMap<String, ClientThread> getClientInfo() {return clientInfo; } // *********************************** Main Method ******************** public static void main(String args[]) {new LiveChatServer(); }}

多個客戶端通過服務(wù)器互相交談

package com.chat;/************************ Live Chat Client *******************/import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.InetAddress;import java.net.socket;import java.net.socketException;public class LiveChatClient { private String chatName;// current user’s chat name(max 7 char if greater than show as 6 // char+... private String serverAddress; // TCP Components private Socket socket; private BufferedReader in; private PrintWriter out; public LiveChatClient() {initHostName();runclient();// have fun } public void initHostName() {try { //replace host name with your computer name or IP address serverAddress = '[hostname]'; if (serverAddress == null)System.exit(1); serverAddress = serverAddress.trim(); if (serverAddress.length() == 0)// empty field {System.out.println('Server IP Address or Name can’t be blank.');initHostName();return; } System.out.println('Trying to connect with server...nServer IP Address:' + serverAddress); // create socket InetAddress inetAddress = InetAddress.getByName(serverAddress); if (!inetAddress.isReachable(60000))// 60 sec {System.out.println('Error! Unable to connect with server.nServer IP Address may be wrong.');System.exit(1); } initPortNo();} catch (SocketException e) { System.out.println('Socket Exception:n' + e); initHostName(); return;} catch (IOException e) { initHostName(); return;} } public void initPortNo() {try { String portNo = '1234'; portNo = portNo.trim(); if (portNo.length() == 0)// empty field {System.out.println('Server port No can’t be blank.');initPortNo();return; } System.out.println('Trying to connect with server...nServer Port No:' + portNo); socket = new Socket(serverAddress, 1234); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getoutputStream(), true);} catch (IOException e) { System.out.println('IO Exception:n' + e); initPortNo(); return;} } public void sendChatName() throws IOException {System.out.println('Enter your name:');BufferedReader br = new BufferedReader(new InputStreamReader(system.in));String name = br.readLine();if (name == null) System.exit(1);// title case (get only first 9 chars of chat name)name = name.trim();if (name.equalsIgnoreCase('All')) { System.out.println('This name is already reserved. Try different one.'); sendChatName(); return;}if (name.length() == 0) { System.out.println('Please enter your chat name.'); sendChatName(); return;}if (name.length() == 1) chatName = String.valueOf(name.charat(0)).toupperCase();if (name.length() > 1 && name.length() < 10) chatName = String.valueOf(name.charat(0)).toupperCase() + name.substring(1).toLowerCase();else if (name.length() > 9) chatName = String.valueOf(name.charat(0)).toupperCase() + name.substring(1, 10).toLowerCase();// sending opcode first then sending chatName to the serverout.println(Opcode.CLIENT_CONNECTEING);out.println(chatName); } public void runclient() {try { sendChatName(); while (true) {int opcode = Integer.parseInt(in.readLine());switch (opcode) { case Opcode.CLIENT_CONNECTEING:// this client is connectingboolean result = Boolean.valueOf(in.readLine());if (result) { System.out .println(chatName + ' is already present. Try different one.'); runclient();}break; case Opcode.CLIENT_CONNECTED:// a new client is connectedInteger totalClient = Integer.valueOf(in.readLine());System.out.println('Total Client:' + totalClient);for (int i = 0; i < totalClient; i++) { String client = in.readLine(); System.out.println((i + 1) + ':' + client);}break;} }} catch (IOException e) { System.out.println('Client is closed...');} } // *********************************** Main Method ******************** public static void main(String args[]) {new LiveChatClient(); }}

服務(wù)器為每個客戶端啟動一個多線程,并包含有關(guān)所有已連接客戶端的信息

package com.chat;/************************ Client Thread *******************/import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.socket;import java.util.HashMap;public class ClientThread implements Runnable { // TCP Components private Socket socket; private BufferedReader in; private PrintWriter out; private String chatName; // seperate thread private Thread thread; // boolean variable to check that client is running or not private volatile boolean isRunning = true; // opcode private int opcode; private HashMap<String, ClientThread> clientInfo = new HashMap<String, ClientThread>(); public ClientThread(Socket socket) {try { this.socket = socket; this.clientInfo = LiveChatServer.getClientInfo(); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getoutputStream(), true); thread = new Thread(this); thread.start();} catch (IOException e) { System.out.println(e);} } public void run() {try { while (isRunning) {if (!in.ready()) continue;opcode = Integer.parseInt(in.readLine());// getting opcode first from clientswitch (opcode) { case Opcode.CLIENT_CONNECTEING:chatName = in.readLine();boolean result = clientInfo.containsKey(chatName);out.println(Opcode.CLIENT_CONNECTEING);out.println(result);if (result)// wait for another chat name if already present continue;// send list of already online users to new online user// for (Object user : clientInfo.keySet().toArray()) {// out.println(Opcode.CLIENT_CONNECTED);// out.println(user.toString());// }// put new entry in clientInfo hashmapclientInfo.put(chatName, this);int i = 0;for (String key : clientInfo.keySet()) { if (key.equals(chatName)) {System.out.println(chatName + ' added at ' + (i + 1) + ' position'); } i++;}// tell other users about new added user and update their online users listfor (ClientThread client : clientInfo.values()) { client.out.println(Opcode.CLIENT_CONNECTED); client.out.println(clientInfo.size()); for (ClientThread client1 : clientInfo.values()) {client.out.println(client1.chatName); }}break;} } // clsoe all connections out.close(); in.close(); socket.close();} catch (IOException e) { System.out.println(e);} }}

這是添加兩個客戶端時的輸出。

服務(wù)器:

ServerSocket[addr=computerName/IPAddress,port=0,localport=1234]computerName:1234Abc added at 1 positionXyz added at 2 position

客戶1:

Trying to connect with server...Server IP Address:computerNameTrying to connect with server...Server Port No:1234Enter your name:abcTotal Client:11:AbcTotal Client:21:Abc2:Xyz

客戶2:

Trying to connect with server...Server IP Address:computerNameTrying to connect with server...Server Port No:1234Enter your name:xyzTotal Client:21:Abc2:Xyz解決方法

我正在為任務(wù)做游戲。我有一個用Java設(shè)置的服務(wù)器和多客戶端,我們正在使用MVC。我需要有一個客戶端將其名稱發(fā)送到服務(wù)器,然后當有兩個玩家出現(xiàn)時,我需要將這兩個名稱以及他們的玩家編號(玩家1或玩家2)發(fā)送回客戶端。我不知道如何分辨信息來自哪個線程或信息被發(fā)送到哪個線程,因此并非所有玩家都認為自己是玩家之一。謝謝。

標簽: java
相關(guān)文章:
主站蜘蛛池模板: 国产精品福利影院 | 欧美日韩无线码免费播放 | 国产精品日韩欧美在线第3页 | 国产精品杨幂va在线观看 | 国产美女91呻吟求 | 97菊爱网 | 欧美曰韩一区二区三区 | 成人久久精品一区二区三区 | 99久久99这里只有免费费精品 | 亚洲狠狠婷婷综合久久久久网站 | 欧美一区二区三区免费不卡 | 高清性色生活片欧美在线 | 国产欧美精品综合一区 | 国产主播在线看 | 国产高清区 | 日韩女同一区二区三区 | 毛片视频网站在线观看 | 国产情侣草莓视频在线 | 手机在线观看黄色网址 | 婷婷欧美| 在线观看免费黄色网址 | 午夜男人一级毛片免费 | 国产免费久久精品 | 国产一区中文字幕在线观看 | 精品国产高清a毛片无毒不卡 | 国产露脸150部国语对白 | 亚洲精品国产精品国自产观看 | 久久精品国产免费一区 | 黄色aaaaa | 日韩精品亚洲人成在线播放 | bbixx在线观看 | 国产精品无码2021在线观看 | 日本爽妇网 | 欧洲欧美人成免费观看 | 免费a大片 | a级片在线观看视频 | 国产 日韩 欧美 高清 | 国产逼逼视频 | 人成免费网站 | 国产精品久久做爰 | japanesefree人妖|