設(shè)想如下:啟動(dòng)服務(wù)端--啟動(dòng)客戶端,鍵入數(shù)據(jù),發(fā)送--服務(wù)端接收數(shù)據(jù),打印出來,鍵入數(shù)據(jù),發(fā)送--客戶端接收數(shù)據(jù),打印出來,鍵入數(shù)據(jù),發(fā)送--如此無限反復(fù)--public?class?Server?{
????static?BufferedReader?br?=?null;
????static?BufferedWriter?bw?=?null;
????static?Scanner?scanner?=?new?Scanner(System.in);
????
????public?static?void?main(String[]?args)?{
??????try?{
??????????ServerSocket?serverSocket?=?new?ServerSocket(8877);
????????System.out.println("這里是服務(wù)端,等待客戶端連接");
????????Socket?socket?=?serverSocket.accept();
????????System.out.println("已和客戶端建立連接");
br?=?new?BufferedReader(new?InputStreamReader(socket.getInputStream()));
bw?=?new?BufferedWriter(new?OutputStreamWriter(socket.getOutputStream()));
Receiver();
}?catch?(IOException?e)?{
e.printStackTrace();
}
}
public?static?void?send()?{
String?info?=?scanner.nextLine();
try?{
bw.write(info);
bw.flush();
}?catch?(IOException?e)?{
e.printStackTrace();
}
Receiver();
}
public?static?void?Receiver()?{
String?info?=?null;
try?{
while?((info?=?br.readLine())?!=?null)?{
System.out.println(info);
}
}?catch?(IOException?e)?{
e.printStackTrace();
}
send();
}
}客戶端類似,也是一個(gè)send()一個(gè)receiver()方法,先調(diào)用send方法發(fā)送然后調(diào)用receiver接收,無限循環(huán)。但執(zhí)行起來在鍵入數(shù)據(jù)后卻無法發(fā)送,按回車發(fā)送不出去,怪事。后來我嘗試另一種寫法,每次在方法里面創(chuàng)建輸入輸出流,然后在finally里面關(guān)閉public?class?Server?{
static?Scanner?scanner?=?new?Scanner(System.in);
static?Socket?socket;
public?static?void?main(String[]?args)?{
try?{
ServerSocket?serverSocket?=?new?ServerSocket(8877);
System.out.println("這里是服務(wù)端,等待客戶端連接");
socket?=?serverSocket.accept();
System.out.println("已和客戶端建立連接");
Receiver();
}?catch?(IOException?e)?{
e.printStackTrace();
}
}
public?static?void?send()?{
String?info?=scanner.nextLine();
try?{
BufferedWriter?bw?=??new?BufferedWriter(new?OutputStreamWriter(socket.getOutputStream()));
bw.write(info);
bw.flush();
}?catch?(IOException?e)?{
e.printStackTrace();
}?finally?{
try?{
socket.shutdownOutput();
}?catch?(IOException?e)?{
e.printStackTrace();
}
Receiver();
}
}
public?static?void?Receiver()?{
String?info?=?null;
try?{
BufferedReader?br?=?new?BufferedReader(new?InputStreamReader(socket.getInputStream()));
while?((info?=?br.readLine())?!=?null)?{
System.out.println(info);
}
}?catch?(IOException?e)?{
e.printStackTrace();
}?finally?{
try?{
socket.shutdownInput();
}?catch?(IOException?e)?{
e.printStackTrace();
}
send();
}
}
}這樣能循環(huán)一次,但后面就提示流=已經(jīng)關(guān)閉,是不是意味著shutdown輸入輸出流后就不能重新打開了?但不關(guān)閉的話又會(huì)出現(xiàn)和上面一樣的情況。請(qǐng)問大神們這樣子到底應(yīng)該怎么寫呢?
添加回答
舉報(bào)
0/150
提交
取消