日期:2014-05-20  浏览次数:20740 次

网络编程出错
package Test;
import java.io.*;
import java.net.*;
public class Server {
public void init(){
ServerSocket server=null;
try{
server=new ServerSocket(port);
while(true){
Socket socket=server.accept();
new Thread(new ServerThread(socket)).start();
}
}catch(IOException e){
e.printStackTrace();
}
finally{
try{
if(server!=null){
server.close();
}
}catch(IOException e){
e.printStackTrace();
}

}
}
public static void main(String[] args) {
new Server().init();
System.out.println("怎么会这样?");

}
int port=30060;

}


package Test;
import java.io.*;
import java.net.*;
public class ServerThread implements Runnable {
public ServerThread(Socket socket){
this.socket=socket;
}
public void run(){
System.out.println("这线程有运行吗?");
BufferedReader reader=null;
PrintStream outPrint=null;
try{
reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
outPrint=new PrintStream(socket.getOutputStream());
String line=null;
if((line=reader.readLine())!=null){
System.out.println(line);
outPrint.print("响应连接");

}
}catch(IOException e){
e.printStackTrace();
try{
if(reader!=null){
reader.close();

}
if(outPrint!=null){
outPrint.close();
}
if(socket!=null){
socket.close();
}
}catch(IOException ex){
ex.printStackTrace();
}
}

}
private Socket socket;

}

package Test;
import java.io.*;
import java.net.*;
public class Client {
public void init(){
Socket socket=null;
BufferedReader reader=null;
PrintStream output=null;
try{

socket=new Socket(IP,port);
reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
output=new PrintStream(socket.getOutputStream());
output.print("请求连接");
String line=null;
while((line=reader.readLine())!=null){
System.out.println(line);
System.out.println("连接成功");
}
}catch(IOException e){
e.printStackTrace();
try{
if(reader!=null){
reader.close();
}
if(output!=null){
output.close();
}
if(socket!=null){
socket.close();
}
}catch(IOException ex){
ex.printStackTrace();
}


}
}
public static void main(String[] args) {
new Client().init();
}
private String IP="192.168.1.102";
private int port=30060;

}


运行上面的网络程序,最后什么也没有输出,也不抛出异常,是哪里线程阻塞吗还是什么问题,请大家指教一下


------解决方案--------------------
这个问题嘛,
首先,
由于BufferedReader的readline方法是一次读一行,所以你用printStream写进去的内容应该含有换行标志, 简单的说output.print("请求连接");换成output.println("请求连接");
outPrint.print("响应连接");换成outPrint.println("响应连接");这样就可以了,so easy,对吧?:)我在机子上调过了,你也试试;
其次,
要是还不行,检查你的private String IP="192.168.1.102"是否正确;
ps:你的close()语句为什么都放在catch块中,建议放到finally中。
 
------解决方案--------------------
Server:
if((line=reader.readLine())!=null){
 System.out.println(line);
 outPrint.print("响应连接");
 }
Client:
while((line=reader.readLine())!=null){
 System.out.println(line);
 System.out.println("连接成功");
 }
服务器端与客户端在没有一方发数据的情况下,都在接收数据,且如果接收不到数据就不发数据。那这样的结果就是在server端判断line时为空,执行finally;或者client判断line为空,继续往下执行。这两种情况任何一个都会使连接断开,程序也就结束。