我有兩個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