📄 session.java
字号:
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;
}
//开始游戏
public void startGame(int id){
int data = Protocol.START<<24|id<<16;
send(data);
}
//向客户端发送数据
synchronized void send(int data) {
try {
dos.writeInt(data);
dos.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//关闭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());
//查询客户端的请求
while(!stop){
int msg = dis.readInt();
int type = msg>>>24;
switch(type){
//游戏玩家连接服务器
case Protocol.SINGUP:{
//注册成功,第二个高字节代表playerID
int data = Protocol.ACK_SINGUP<<24|sessionId<<16;
dos.writeInt(data);
dos.flush();
break;
}
//用户开始游戏,每走一步传输一次
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();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -