当前位置: 代码迷 >> Java相关 >> java Socket编程,客户端要发送两次数据服务器才接受一次,为啥?该如何处理
  详细解决方案

java Socket编程,客户端要发送两次数据服务器才接受一次,为啥?该如何处理

热度:1718   发布时间:2013-02-25 21:48:47.0
java Socket编程,客户端要发送两次数据服务器才接受一次,为啥?
小弟写的客户端服务器小程序,要求做到客户端由键盘输入一个数据,服务器能收到并显示在logcat里,小弟的程序如下:
客户端程序:

package jack.netprogram;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientThread extends Thread{

public void run(){
try {
Socket socket = new Socket("10.92.1.28", 1804);
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
PrintWriter os = new PrintWriter(socket.getOutputStream());

String readline = null;
System.out.println("Client input:");
readline = sin.readLine();
while(!readline.equals("bye")){
os.println(readline);
os.flush();
System.out.println("Client send:" + readline);
readline = sin.readLine();
}
os.close();
socket.close();
} catch (UnknownHostException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}
}
服务器程序:

package jack.netprogram;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ServerThread extends Thread{

public void run(){
try {
String receive = null;
ServerSocket server = new ServerSocket(1804);
Socket socket = server.accept();
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
receive = is.readLine();
while(receive != null ){
System.out.println("Server receive:" + is.readLine());
receive = is.readLine();
if(receive == null)
break;
}
is.close();
socket.close();
server.close();
} catch (UnknownHostException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}
}
主程序:

package jack.netprogram;

public class ClientServer {

public static void main(String args[]){
ClientThread client = new ClientThread();
ServerThread server = new ServerThread();
server.start();
client.start();
}
}


程序运行的结果却是:

Client input:
123
Client send:123
abc
Client send:abc
Server receive:abc
dfg
Client send:dfg
ggg
Server receive:ggg
Client send:ggg
bye

我的疑问在:为什么客户端每隔一次放松的数据才能被服务器接受,而不是每次都能接收。
还有,如果我不想用bye作为结束标志,想换成回车键作为结束标志的话该怎么改代码?

------解决方案--------------------------------------------------------
Java code
receive = is.readLine();while(receive != null ){System.out.println("Server receive:" + [color=#FF0000]is.readLine[/color]());receive = [color=#FF0000]is.readLine()[/color];
------解决方案--------------------------------------------------------
Java code
receive = is.readLine();while(receive != null ){System.out.println("Server receive:" + is.readLine());receive = is.readLine();
  相关解决方案