标题:
Java socket和多线程(Thread)实例
[打印本页]
作者:
qingqing3721
时间:
2011-7-16 13:56
标题:
Java socket和多线程(Thread)实例
1. socket通信:有客户端和效劳端的socket代码。
2. 多线程:客户端和效劳端各用一线程发送信息;效劳端另有一监听线程, 用于把超时的信息删除。
这里应用到了同步, 使两个线程可以操作同一个map。
代码:(类全在同一个包内)
server端:
import java. io. BufferedReader;
import java. io. InputStreamReader;
import java. io. PrintWriter;
import java. ServerSocket;
import java. Socket;
import java. util. Collections;
import java. util. concurrent. TimeUnit;
import java. util. HashMap;
import java. util. Map;
public class ServerNet {
// 以毫秒为单位
private final static long timeLimit = 10000 ;
private MapString, String map = Collections. synchronizedMap(new HashMapString, String());
public void ServerSocketNet(){
try{
ServerSocket ss = new ServerSocket(6060);
Socket s = ss. accept();
// 用于获取客户端传输来的信息
BufferedReader buff = new BufferedReader(new InputStreamReader(s. getInputStream()));
// 用于获取效劳端预备响应的信息
BufferedReader in = new BufferedReader(new InputStreamReader(System. in));
// 发送效劳端预备响应的信息
PrintWriter pw = new PrintWriter(s. getOutputStream(), true);
pw. println("您已经成功树立连接!");
new ServerOutNet(pw, in);
new ServerTimeListener(map, timeLimit);
// 显示客户端的传输来的信息
while(true){
String str = buff. readLine();
if(str. equals("exit")){
break;
}else{
map. put(ServerHelper. getInstance(). getMapKey(), str);
System. out. println(str + " map. size: " + map. size());
}
System. out. println("To Client:");
Thread. sleep(100);
}
s. close();
}catch(Exception e){
e. printStackTrace();
}
}
public static void main(String[] args){
new ServerNet(). ServerSocketNet();
}
}
/**
* server发送线程 向客户端发送响应信息
* @author ids-user
*
*/
class ServerOutNet extends Thread{
private PrintWriter printWriter;
private BufferedReader bufferedReader;
ServerOutNet(PrintWriter pw, BufferedReader in){
this. printWriter = pw;
this. bufferedReader = in;
start();
}
public void run(){
while(true){
try{
String inStr = bufferedReader. readLine();
if(inStr.
姿美堂
equals("exit")){
printWriter. close();
bufferedReader. close();
break;
}else{
printWriter. println("From Server: " + inStr);
}
sleep(300);
}catch(Exception e){
printWriter = null;
bufferedReader = null;
throw new RuntimeException(e);
}
}
}
}
// 时间监听线程类。
class ServerTimeListener extends Thread{
private long timeLimit;
MapString, String map = new HashMapString, String();
// 单例
// private ServerTimeListener(){}
// private final static ServerTimeListener stl = new ServerTimeListener();
// public static ServerTimeListener getInstance(){
// return stl;
// }
ServerTimeListener(MapString, String map , long timeLimit){
this. map = map;
this. timeLimit = timeLimit;
start();
}
欢迎光临 编程开发论坛 (http://bbs.lihuasoft.net/)
Powered by Discuz! 6.0.0