Skip to content

Instantly share code, notes, and snippets.

@krsnvijay
Created October 1, 2019 02:05
Show Gist options
  • Save krsnvijay/b6dc9f60177c7037ab1e44db3b977539 to your computer and use it in GitHub Desktop.
Save krsnvijay/b6dc9f60177c7037ab1e44db3b977539 to your computer and use it in GitHub Desktop.
Simple Java Socket
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.Timestamp;
public class Client {
public static void main(String[] args) {
Socket client;
DataOutputStream dos;
InetAddress ia;
try {
ia = InetAddress.getByName("localhost");
client = new Socket(ia, 9999);
dos = new DataOutputStream(client.getOutputStream());
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
dos.writeUTF(timestamp.toString());
client.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
ServerSocket server;
Socket client;
DataInputStream dis;
try {
server = new ServerSocket(9999);
System.out.println(server.getLocalSocketAddress());
for (int i = 0; i < 5; i++) {
client = server.accept();
System.out.println("Connected " + client.getRemoteSocketAddress());
dis = new DataInputStream(client.getInputStream());
System.out.println(dis.readUTF());
client.close();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment