?? client.java
字號:
/*
* Pasi Manninen 21.4.2007
* http://ptm.fi
*/
// import necessary libraries for communication
import java.io.*;
import java.net.*;
import java.util.*;
// every Flash client has own client in Server
public class Client extends Thread {
private Thread thrThis; // client thread
private Socket socket; // socket for connection
private XMLSocketServer server; // server which the client is connected
private BufferedReader in; // captures incoming messages
private PrintWriter out; // sends outgoing messages
private String loginName; // users loginname
private String id; // users unique ID
private boolean inGame; // is user inGame
// constructor - initialize client
public Client(XMLSocketServer server, Socket socket, String id) {
this.server = server;
this.socket = socket;
this.id = id;
// initialize reader and writer for connection
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
} catch(IOException ioe) {
System.out.print("Problem with initializing a new client");
killClient();
}
}
// client has own thread (read and write to socket)
public void run() {
try {
// read all data from client (one char at once)
char charBuffer[] = new char[1];
while(in.read(charBuffer,0,1) != -1) {
// save message to StringBuffer, wait for null "\0"
StringBuffer stringBuffer = new StringBuffer(8192);
while(charBuffer[0] != '\0') {
stringBuffer.append(charBuffer[0]);
in.read(charBuffer, 0 ,1);
}
// send message to XML Socket Server (and then to other clients)
server.broadcastMessage(stringBuffer.toString());
}
} catch(IOException ioe) {
System.out.print("Cannot read data from client");
} finally {
killClient();
}
}
// set client's loginname
public void setLoginName(String name){
this.loginName = name;
}
// return client's loginname
public String getLoginName(){
return this.loginName;
}
// is user ingame
public boolean isIngame(){
return this.inGame;
}
// return users unique id
public String returnId(){
return this.id;
}
// send message to Flash client
public void send(String message) {
// send message to client
out.print(message);
// clear and check errors
if (out.checkError()) {
System.out.print("Cannot send data to client");
killClient();
}
}
// kill this client (logout or connection dropped)
private void killClient() {
// remove client from servers client list (HasMap)
server.removeClient(id);
// close all resources of this client
try {
in.close();
out.close();
socket.close();
thrThis = null;
} catch (IOException ioe) {
System.out.print("Cannot close client");
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -