我想從客戶端和服務器發送多個字節數組?通過套接字發送多個字節數組
我能夠發送/從客戶端接收一個字節數組,併發送/從服務器接收一個字節數組:
我的代碼是這樣的:
服務器:
Socket sock=null;
ByteArrayOutputStream input=null;
OutputStream out=null;
InputStream in=null;
try{
ServerSocket server_sock=new ServerSocket(2972);
sock=server_sock.accept();
in =
sock.getInputStream();
out=sock.getOutputStream();
}catch(IOException e){
System.out.println(e.getMessage());
}
String word="";
//1-Receive
try{
ByteArrayOutputStream serverinput=new ByteArrayOutputStream();
int len=0;
byte[] buf=new byte[1000];
while ((len = in.read(buf))>=0) {
serverinput.write(buf, 0, len);
}
sock.shutdownInput();
word=new String(serverinput.toByteArray());
System.out.println("Client send 1"+word);
}catch(Exception e){
System.out.println(e.getMessage());
}
String st="Server is a king";
try{
out.write(st.getBytes());
out.flush();
}catch(Exception e){
System.out.println(e.getMessage());
}
客戶:
Socket sock=null;
OutputStream out=null;
InputStream in=null;
try{
sock=new Socket("127.0.0.1",2972);
}catch(IOException e){
System.out.println(e.getMessage());
}
String word="Hellow World" ;
try{
in =
sock.getInputStream();
out=sock.getOutputStream();
}catch(IOException e){
System.out.println(e.getMessage());
}
//1- send
try{
System.out.println("Your string is"+word+"converted to byte"+word.getBytes());
out.write(word.getBytes());
out.flush();
sock.shutdownOutput();
}catch(Exception e){
System.out.println(e.getMessage());
}
try{ ByteArrayOutputStream serverinput=new ByteArrayOutputStream();
int len=0;
byte[] buf=new byte[1000];
while ((len = in.read(buf))>=0) {
serverinput.write(buf, 0, len);
}
System.out.println("server send 1 "+new String(serverinput.toByteArray()));
System.out.println("Your string is"+word+"converted to byte"+word.getBytes());
}catch(Exception e){
System.out.println(e.getMessage());
}
此代碼工作正常,從客戶端和服務器提交,但它不工作時,我想發送/接收更多的字節數組?
它只在我使用shutdown時工作,因爲客戶端和服務器都讀寫數據。
因此,我不能再次使用套接字通道...是否有其他解決方案? ......這不會導致僵局。
這是工作...非常感謝。 – 2011-04-29 22:44:32
不錯的答案,它也適用於我!謝謝。 – cabreracanal 2011-10-04 10:21:22
@Javalover ...呃,你想在工作之後分享代碼嗎? – gumuruh 2014-08-21 23:37:44