Skip to content

Instantly share code, notes, and snippets.

@defaultlocale
Last active Apr 4, 2018
Embed
What would you like to do?
Client example
import java.io.*;
import java.net.*;
import static java.lang.System.out;
public class Client {
public static void main(String args[]) throws Exception{
try(Socket socket = new Socket("127.0.0.1", 8081);
DataInputStream dis =new DataInputStream(socket.getInputStream());) {
int pong1 = dis.readInt();
int pong2 = dis.readInt();
out.println("Received: "+pong1);
out.println("Received: "+pong2);
}
}
}
import java.io.*;
import java.net.*;
import static java.lang.System.out;
public class SocketServer {
public static void main(String[] args) throws Exception{
out.println("Server started");
try(ServerSocket server = new ServerSocket(8081)) {
while (true) {
send(server.accept());
}
}
}
private static void send(Socket socket) throws Exception {
try(DataOutputStream dos = new DataOutputStream(socket.getOutputStream())) {
int value = 1;
dos.writeInt(123);
dos.writeInt(value);
dos.flush();
out.println("Sent: "+value);
} finally {
socket.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment