刚学了Socket编程,想拓展一下.与连接池一起用.增加其可用性.
自己写了下,运行没得到想要的结果.不知道错在哪里,所以只能请各位帮忙了.
Server端:
package pool;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable{
protected static int maxLeng;
private static int port;
private static ServerSocket server;
public Server() {
}
public Server(int port,int maxLength){
this.port=port;
this.maxLeng=maxLength;
}
public void run(){
try {
server=new ServerSocket(port,maxLeng);//创建一个最大链接次数为5次的ServerSocket.
Socket socket=server.accept();
pool.addSocket(socket);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server=new Server(9090,5);
server.run();
}
}
pool and cilent:
package pool;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;
public class pool implements Runnable{
private static List poolList=new LinkedList();
private Socket socket;
private String ip;
private int port;
public pool() {
// TODO Auto-generated constructor stub
}
public pool(String ip,int port){
this.ip=ip;
this.port=port;
}
public static void addSocket(Socket socket){
synchronized (poolList) {//将连接池同步起来
poolList.add(poolList.size(),socket);
poolList.notifyAll();
}
}
public void make(){
try {
socket=new Socket(ip,port);
File file=new File("e:\\我的工号.txt");
BufferedReader read=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String tempStr="";
String temp=null;
PrintWriter pw=new PrintWriter(socket.getOutputStream());
while((temp=read.readLine())!=null){
tempStr+=(temp+"\r");
}
pw.write(tempStr);
pw.close();
read.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while(true){
synchronized (poolList) {
while(poolList.isEmpty()){
try {
poolList.wait();
} catch (InterruptedException e) {
return;
}
}
Socket socket=(Socket)poolList.remove(0);
}
make();
}
}
public static void main(String[] args) {
add();
}
public static void add(){
for(int i=0;i<Server.maxLeng;i++){
pool p=new pool("10.43.9.51",9090);
new Thread(p,i+"").start();
}
}
}
本来是希望通过Socket多线程的读文件.现在运行出现的结果没有报错.也没有任何内容输出.(注:操作步骤没有问题的.)