【发布时间】:2014-11-13 06:16:31
【问题描述】:
我有以下几段代码,但不完全理解它们的行为方式。
客户
public class Client {
public static void main(String[] args) throws InterruptedException {
try {
final Socket socket = new Socket("localhost", 3011);
final OutputStream socketStream = socket.getOutputStream();
for (int i = 0; i < 10; i++) {
final byte[] message = new byte[1 * 1000 * 1000];
socketStream.write(message);
socketStream.flush();
System.out.println("sent message");
}
socketStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器:
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {
final int portNumber = 3011;
try {
ServerSocket serverSocket = new ServerSocket(portNumber);
System.out.println("server running on " + portNumber);
while (true) {
final Socket clientSocket = serverSocket.accept();
final InputStream inputStream = clientSocket.getInputStream();
final byte[] in = new byte[1024];
long start = System.currentTimeMillis();
int totalBytesRead = 0;
int bytesRead;
while((bytesRead = inputStream.read(in)) >= 0) {
totalBytesRead += bytesRead;
}
long duration = System.currentTimeMillis() - start;
System.out.println("got " + totalBytesRead + " bytes from socket");
System.out.println("took " + duration + "ms");
final double transferRatePerSecond = totalBytesRead / (duration / 1000f);
System.out.println("average transfer was " + transferRatePerSecond + " bytes/second");
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
现在我希望看到的是在服务器端收到 10 条单独的消息。我实际上得到的是一条消息,它似乎是客户端发送的所有 10 条消息的总和。例如:
got socket Socket[addr=/5.67.133.157,port=53432,localport=3011]
got 10000000 bytes from socket
took 69332ms
average transfer was 144233.546875 bytes/second
【问题讨论】:
-
你能解释一下为什么你认为你应该收到 10 条消息吗?您正在创建一个大的 1Mb 空字节缓冲区并发送它
-
是的 - 但我发送了 10 次,中间会刷新流。
-
为什么需要使用套接字? WCF 是一个框架,可以为您处理所有这些低级别的事情。
-
因为我想了解Sockets...
标签: java sockets networking