当前位置: 技术问答>java相关
急!帮忙看看错在哪里?
来源: 互联网 发布时间:2015-05-11
本文导语: 诸兄: 小弟在编一个通信服务器程序,结果总抛出错误,请指教。(线程run方法如下) public void run() { String msg=null; String userName=null; String password=null; try { ...
诸兄:
小弟在编一个通信服务器程序,结果总抛出错误,请指教。(线程run方法如下)
public void run()
{
String msg=null;
String userName=null;
String password=null;
try
{
while(true)
{
Socket socket=serverSocket.accept();
inStream=new DataInputStream(socket.getInputStream());
outStream=new DataOutputStream(socket.getOutputStream());
......
}
}
catch(Exception e)
{
System.out.println("ERR:RUN sever" );
System.out.println(e.toString()");
}
}
错误提示如下:
ERR:RUN sever
java.net.SocketException: Socket closed
小弟在编一个通信服务器程序,结果总抛出错误,请指教。(线程run方法如下)
public void run()
{
String msg=null;
String userName=null;
String password=null;
try
{
while(true)
{
Socket socket=serverSocket.accept();
inStream=new DataInputStream(socket.getInputStream());
outStream=new DataOutputStream(socket.getOutputStream());
......
}
}
catch(Exception e)
{
System.out.println("ERR:RUN sever" );
System.out.println(e.toString()");
}
}
错误提示如下:
ERR:RUN sever
java.net.SocketException: Socket closed
|
是不是循环的时候实例化了很多个Socket对象的缘故呀
while(true)
{
Socket socket=serverSocket.accept();
inStream=new DataInputStream(socket.getInputStream());
outStream=new DataOutputStream(socket.getOutputStream());
......
}
while(true)
{
Socket socket=serverSocket.accept();
inStream=new DataInputStream(socket.getInputStream());
outStream=new DataOutputStream(socket.getOutputStream());
......
}
|
你应该把accept拿到每道线程的死循环外面来:
这是一个单线程的例子:
public void listenSocket(){
try{
server = new ServerSocket(7456);
client = server.accept();
} catch (IOException e) {
System.out.println(e.toString());
System.exit(-1);
}
try{
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("Accept failed: 7456");
System.exit(-1);
}
//accept应该在while外面
while(true){
try{
line = in.readLine();
//Send data back to client
out.println(line);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
这是一个单线程的例子:
public void listenSocket(){
try{
server = new ServerSocket(7456);
client = server.accept();
} catch (IOException e) {
System.out.println(e.toString());
System.exit(-1);
}
try{
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("Accept failed: 7456");
System.exit(-1);
}
//accept应该在while外面
while(true){
try{
line = in.readLine();
//Send data back to client
out.println(line);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
|
你需要建立一个与客户的ServerConn。
|
每ServerSocket接收到一个连接(Socket)新建一个线程,同时把连接好的Socket当作参数传给线程实例,也就是把Socket当作构造方法的参数。