Socket客戶端循環(huán)發(fā)送多條信息給服務端,發(fā)一次socket自動關閉?
目的:通過Socket客戶端發(fā)送多條數(shù)據(jù)給服務端
錯誤:
我是客戶端0,服務器說:歡迎您!
java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Socket.java:912)
at com.imooc.MultiClient.main(MultiClient.java:23)
方法:
//1.創(chuàng)建客戶端Socket,指定服務器地址和端口
Socket socket=new Socket("localhost", 8888);
//2.通過for循環(huán)發(fā)送多條數(shù)據(jù)
for(int i=0;i<6;i++){
//獲取輸出流,向服務器端發(fā)送信息
OutputStream os=socket.getOutputStream();//字節(jié)輸出流
PrintWriter pw=new PrintWriter(os);//將輸出流包裝為打印流
pw.write("用戶名:"+i+";密碼:789");
pw.flush();
socket.shutdownOutput();//關閉輸出流
//獲取輸入流,并讀取服務器端的響應信息
InputStream is=socket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String info=null;
while((info=br.readLine())!=null){
System.out.println("我是客戶端"+i+",服務器說:"+info);
}
//關閉資源
br.close();
is.close();
pw.close();
os.close();
}
//3、關閉socket
socket.close();
2020-03-31
123
2016-12-10
你看一下5-1,也許就明白了