标签:
public class MSGThread extends Thread{
private Socket fromClient;
public MSGThread(Socket fromClient){
this.fromClient = fromClient;
}
public void run(){
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(
fromClient.getInputStream()));
String str = br.readLine();
String[] allMsg = str.split("&");
Date sendTime = new Date(Long.parseLong(allMsg[2]));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(sendTime));
System.out.println(allMsg[0] + "说:" + allMsg[1]);
// System.out.println("对方说:" + str);
// System.out.println(fromClient.getInetAddress().getHostAddress());
} 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(this.fromClient != null){
try {
this.fromClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class TestServer {
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server = null;
try {
server = new ServerSocket(9527);
System.out.println("开始监听......");
while (true) {
// accept是阻塞方法,直到监听到客户端发送过来的消息
Socket fromClient = server.accept();
// InputStream in = fromClient.getInputStream();
// byte[] b = new byte[1024];
// int length = 0;
// String str = "";
// while((length = in.read(b)) != -1){
// String tmp = new String(b, 0, length);
// str += tmp;
// }
new MSGThread(fromClient).start();
}
} 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();
}
}
}
}
}
标签:
原文地址:http://www.cnblogs.com/zzj951103/p/5598389.html