Created
October 1, 2019 02:05
-
-
Save krsnvijay/b6dc9f60177c7037ab1e44db3b977539 to your computer and use it in GitHub Desktop.
Simple Java Socket
This file contains hidden or 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.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(); | |
} | |
} | |
} |
This file contains hidden or 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.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