Created
October 23, 2011 13:34
-
-
Save freewind/1307363 to your computer and use it in GitHub Desktop.
Socket Server and Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.InputStream; | |
import java.net.Socket; | |
public class Client { | |
static int PORT = 6666; | |
public static void main(String[] args) throws Exception { | |
Socket socket = new Socket("127.0.0.1", PORT); | |
InputStream input = socket.getInputStream(); | |
long total = 0; | |
long start = System.currentTimeMillis(); | |
byte[] bytes = new byte[10240]; // 10K | |
while (true) { | |
int read = input.read(bytes); | |
total += read; | |
long cost = System.currentTimeMillis() - start; | |
if (cost > 0) { | |
System.out.println("Read " + total + " bytes, speed: " + total / cost + "KB/s"); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.OutputStream; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
import java.util.Arrays; | |
public class Server { | |
public static final int SPEED = 100; // KBytes | |
public static void main(String[] args) throws Exception { | |
ServerSocket server = new ServerSocket(6666); | |
Socket socket = server.accept(); | |
OutputStream output = socket.getOutputStream(); | |
byte[] bytes = new byte[10 * 1024]; // 10K | |
Arrays.fill(bytes, (byte) 1); | |
for (int i = 1;; i++) { | |
long start = System.nanoTime(); | |
for (int k = 0; k < SPEED / 10; k++) { | |
setId(bytes, i); | |
output.write(bytes); | |
} | |
long end = System.nanoTime(); | |
long cost = (end - start) / 1000000; | |
if (cost < 1000) { | |
Thread.sleep(1000 - cost); | |
} else { | |
System.out.println("Sorry, the speed is too slow, it uses more than 1s: " + cost + "ms"); | |
} | |
System.out.println("Sending " + SPEED + "K data cost " + cost + "ms, waiting for next second"); | |
} | |
} | |
public static void setId(byte[] bytes, int id) { | |
bytes[0] = (byte) (id >>> 24); | |
bytes[1] = (byte) (id >>> 16); | |
bytes[2] = (byte) (id >>> 8); | |
bytes[3] = (byte) id; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment