随手做的一个简单的Socket服务器,用来模拟全向移动平台机上控制器的响应的,配合全向移动平台手机控制器调试用的。
在主线程里死循环监听端口12000,有客户端连接就新建一个子线程,在子线程里接受客户端数据(byte[10],每个字节分别定义了运动状态、运动速度等信息),进行解析,在控制台显示当前速度或状态,回传数据。客户端退出则关闭子线程,返回主线程继续等待连接。
命令行运行 java -jar 程序名.jar
完整源码
http://download.csdn.net/detail/kagami1983/8807765
主线程代码:
public SocketServerForMecanum() {
try {
serverSocket = new ServerSocket(12000);
} catch (IOException e) {
//e.printStackTrace();
System.out.println("Create ServerSocket Error...");
}
}
@Override
public void run() {
while (true) {
System.out.println("Listenning...");
try {
// 每个请求交给一个线程去处理
socket = serverSocket.accept();
ServerThread serverThread = new ServerThread(socket);
serverThread.start();
sleep(1000);
} catch (Exception e) {
//e.printStackTrace();
System.out.println("Create Socket Error...");
}
}
}
子线程代码:
class ServerThread extends Thread {
private Socket socket;
private InputStream ins;
private OutputStream ous;
private byte[] buffer_received = new byte[10];
private short moveX = 0, moveY = 0, rotate = 0;
private int recount = 0;
public ServerThread(Socket socket) {
// super();
this.socket = socket;
try {
ins = socket.getInputStream();
ous = socket.getOutputStream();
} catch (IOException e) {
//e.printStackTrace();
System.out.println("Create ServerThread Error...");
}
}
@Override
public void run() {
while (true) {
try {
ins.read(buffer_received);
if (recount >= 5) {
recount = 0;
moveX = 0;
moveX = (short) (buffer_received[5] & 0x00ff);
moveX <<= 8;
moveX |= (buffer_received[4] & 0x00ff);
moveY = 0;
moveY = (short) (buffer_received[7] & 0x00ff);
moveY <<= 8;
moveY |= (buffer_received[6] & 0x00ff);
rotate = 0;
rotate = (short) (buffer_received[9] & 0x00ff);
rotate <<= 8;
rotate |= (buffer_received[8] & 0x00ff);
System.out.println("moveX=" + moveX + ";" + "moveY="
+ moveY + ";" + "rotate=" + rotate + ";");
} else {
recount++;
}
/*//buffer的头字节为2,则认为收到了客户端主动请求关闭连接
if (buffer_received[0] == 2) {
ins.close();
ous.close();
socket.close();
return;
}*/
//模拟上电
if (buffer_received[2] == 1) {
System.out.println("Power ON...");
}
//模拟下电
if (buffer_received[2] == 2) {
System.out.println("Power OFF...");
}
//模拟停止
if (buffer_received[2] == 4) {
System.out.println("Stop Button Pushed!...");
}
//将首字节置1然后回传
buffer_received[0] = 1;
ous.write(buffer_received);
} catch (IOException e) {
//e.printStackTrace();
System.out.println("Client Disconnected...");
//当客户端因各种原因关闭连接而且没有通知服务端的,包括屏幕翻转、打开首选项等情况
try {
ins.close();
ous.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return;
}
}
}
}