?? session.java
字號(hào):
package com.j2medev.chapter5;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Session extends Thread{
private Socket socket = null;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean stop = false;
private int sessionId = 0;
private Room room = null;
public Session(Socket socket){
this.socket = socket;
}
public void setSessionId(int id){
this.sessionId = id;
}
public int getSessionId(){
return sessionId;
}
public void setRoom(Room room){
this.room = room;
}
public Room getRoom(){
return room;
}
//開(kāi)始游戲
public void startGame(int id){
int data = Protocol.START<<24|id<<16;
send(data);
}
//向客戶端發(fā)送數(shù)據(jù)
synchronized void send(int data) {
try {
dos.writeInt(data);
dos.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//關(guān)閉Session
public void closeSession(){
try {
if(dis != null){
dis.close();
dis = null;
}
if(dos != null){
dos.close();
dos = null;
}
if(socket != null){
socket.close();
socket = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void run(){
try {
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
//查詢客戶端的請(qǐng)求
while(!stop){
int msg = dis.readInt();
int type = msg>>>24;
switch(type){
//游戲玩家連接服務(wù)器
case Protocol.SINGUP:{
//注冊(cè)成功,第二個(gè)高字節(jié)代表playerID
int data = Protocol.ACK_SINGUP<<24|sessionId<<16;
dos.writeInt(data);
dos.flush();
break;
}
//用戶開(kāi)始游戲,每走一步傳輸一次
case Protocol.STEP:{
room.delegate(msg);
break;
}
//用戶退出游戲
case Protocol.QUIT:
case Protocol.WIN:
{
room.delegate(msg);
stop = true;
break;
}
default:
break;
}
}
closeSession();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -