import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TestServer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//1、创建服务器监听器
ServerSocket server = null;
try {
server = new ServerSocket(9527);
//2、开始监听
System.out.println("开始监听......");
while(true){
Socket socket = server.accept();//accept会进入阻塞状态,一旦有消息发送过来,就返回Socket对象
//3、开启子线程进行消息处理
new ProcessThread(socket);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(server != null){
try {
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class ProcessThread extends Thread{
private Socket socket;
public ProcessThread(Socket socket){
this.socket = socket;
this.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
//3、从Socket的InputStream取数据
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = br.readLine();
System.out.println("接收的消息:" + msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}