我有两个java类一个是服务器,另一个是客户端。假设我需要从服务器向客户端发送100 MB数据的情况。当我发送此消息时,服务器是否等待直到客户端读取? 如果你看代码,服务器的endTime变量在客户端读取100 MB发送之前是否取值?当服务器套接字写入时,它是否等到客户端套接字读取?
服务器类:
public class MyServerSocket {
private ServerSocket providerSocket;
private Socket connection = null;
private ObjectOutputStream out;
private ObjectInputStream in;
private String message;
public static void main(String[] args) {
MyServerSocket m = new MyServerSocket ();
m.establishConnection();
}
public void establishConnection(){
//SETUP CONNECTION
providerSocket = new ServerSocket(2004, 10);
connection = providerSocket.accept();
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connectiongetInputStream());
//END SETUP CONNECTION
//Suppose this String contains 100 MB
String x = "Send 100MB of data";
sendMessage("Server sends string x");
//Here is the doubt
String startTime = System.nanotime();
sendMessage(x);
String endTime = System.nanotime();
do{
message = (String)in.readObject();
if (message.contains("bye")){
System.out.println("Server receives bye from Client");
}
}while(!message.contains("bye"));
}
public void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
客户班组长:
public class MyClientSocket {
private Socket requestSocket;
private ObjectInputStream in;
private ObjectOutputStream out;
private String message;
public static void main(String[] args) {
MyClientSocket n = new MyClientSocket();
n.establishConnection();
}
public void establishConnection(){
requestSocket = new Socket("localhost", 2004);
in = new ObjectInputStream(requestSocket.getInputStream());
out = new ObjectOutputStream(requestSocket.getOutputStream());
do{
if(message instanceof String){
message = (String)in.readObject();
}else{
message = "";
}
if(message.contains("Server sends string x")){
//The following line reads the 100 MB String
String x = (String)in.readObject();
sendMessage("bye");
}
}while(!message.contains("bye"));
}
public void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
在此先感谢
'通常不'应该是'从不'。任何时候写入都必须阻塞它是因为发送缓冲区之外有一些东西需要发送。当发送缓冲区中已经发送和确认的内容被阻塞时,它会被阻塞,但是当最后一位被复制到发送缓冲区时,它会毫不犹豫地返回。 – EJP