tcp/ip socke通信

这两天一直为写一个tcp/ip简单的通信的失败而苦恼,经过一天多的查询终于找到了错误的所在,大家一定要记住在通信的过程中如果碰到向程序外写的流,一定要注意在写完这个流之后清理缓冲区。否则通信会处于阻塞的状态。
public class TcpServer  {
public static void main(String []args) throws Exception{

ServerSocket ss = new ServerSocket(6666);
try{
Socket s = ss.accept();
System.out.println("a Client come in");

BufferedReader sbr = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter spw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader sbr2 = new BufferedReader(new InputStreamReader(System.in));
String content = " ";
String scontent = " ";
content = sbr.readLine();
while(!content.equals("bye")) {

System.out.println("Client:"+content);
scontent = sbr2.readLine();
System.out.println("Server:"+scontent);
spw.println(scontent);
spw.flush();// 一定要注意呀
content = sbr.readLine();
}


spw.close();
s.close() ;
sbr.close();
}catch(Exception e) {
System.out.println("problem");
}

}
}

你可能感兴趣的:(socket)