服務(wù)器返回消息后,就自動(dòng)停了!什么原因,求大神幫助
//服務(wù)器端 package?com.example.demo; import?java.io.BufferedReader; import?java.io.BufferedWriter; import?java.io.InputStreamReader; import?java.io.OutputStreamWriter; import?java.net.ServerSocket; import?java.net.Socket; public?class?ServerSoket?{ public?static?void?main(String[]?args)?{ ServerSoket?serverSoket?=?new?ServerSoket(); serverSoket.init(); } private?void?init()?{ //?TODO?Auto-generated?method?stub ServerSocket?server?=?null; BufferedReader?bf?=?null; BufferedWriter?bw?=?null; try?{ server?=?new?ServerSocket(9898); Socket?socket?=?server.accept(); bf?=?new?BufferedReader(new?InputStreamReader(socket.getInputStream())); bw?=?new?BufferedWriter(new?OutputStreamWriter(socket.getOutputStream())); String?line?=?null; if((line?=?bf.readLine())!=null){ System.out.println(line); bw.write("respond:"+line?+"\n"); bw.flush(); } }?catch?(Exception?e)?{ //?TODO?Auto-generated?catch?block e.printStackTrace(); } } } //客戶端 package?com.example.demo; import?java.io.BufferedReader; import?java.io.BufferedWriter; import?java.io.IOException; import?java.io.InputStreamReader; import?java.io.OutputStreamWriter; import?java.net.InetAddress; import?java.net.Socket; public?class?ClientScoket?{ public?static?void?main(String[]?args)?{ ClientScoket?clientScoket?=?new?ClientScoket(); clientScoket.start(); } private?void?start()?{ //?TODO?Auto-generated?method?stub Socket?client?=null;? BufferedReader?bf??=?null; BufferedWriter?bw?=?null; BufferedReader?bfServer?=?null; bf?=?new?BufferedReader(new?InputStreamReader(System.in)); try?{ client?=?new?Socket(InetAddress.getLocalHost(),?9898); bfServer?=?new?BufferedReader(new?InputStreamReader(client.getInputStream())); bw?=?new?BufferedWriter(new?OutputStreamWriter(client.getOutputStream())); String?line?=?null; String?res?=?null; while(!(line=bf.readLine()).equalsIgnoreCase(("bye"))){ // 這里非常重要,一定要加上這個(gè)\n bw.write(line?+"\n"); bw.flush(); res?=?bfServer.readLine(); System.out.println(res); } }?catch?(Exception?e)?{ //?TODO?Auto-generated?catch?block e.printStackTrace(); }finally{ try?{ bf.close(); }?catch?(IOException?e)?{ //?TODO?Auto-generated?catch?block e.printStackTrace(); } } } }
為什么服務(wù)器端返回消息之后就關(guān)了,然后客戶端再發(fā),就報(bào)Connection reset by peer: socket write error異常
2016-06-11
謝謝,知道了!
2016-06-01
我也認(rèn)為視頻中的服務(wù)器端代碼有問(wèn)題,那個(gè)socket.accept應(yīng)該在一個(gè)while循環(huán)里才能不斷接收來(lái)自客戶端的消息,這樣寫也就是只能接受一次啊,不知道郭嬸兒是怎么接收兩次的,是不是視頻做了手腳o(^▽^)o
2016-05-17
服務(wù)器端讀取客戶端的代碼寫錯(cuò)了