Created
February 10, 2020 18:20
-
-
Save khalefa-phd/cbcb91c67b2958f2e9d71529c75cf456 to your computer and use it in GitHub Desktop.
Socket IP example 1
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.util.Scanner; | |
import java.net.Socket; | |
import java.io.IOException; | |
/** | |
* A command line client for the date server. Requires the IP address of | |
* the server as the sole argument. Exits after printing the response. | |
*/ | |
public class Client { | |
public static void main(String[] args) throws IOException { | |
if (args.length != 1) { | |
System.err.println("Pass the server IP as the sole command line argument"); | |
return; | |
} | |
//Create a client socket | |
//first argument is ip | |
//second is port | |
Socket socket = new Socket(args[0], 1090); | |
//get the input stream of sockets | |
Scanner in = new Scanner(socket.getInputStream()); | |
//read from the inputstream | |
System.out.println("Server response: " + in.nextLine()); | |
} | |
} |
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.IOException; | |
import java.io.PrintWriter; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
import java.util.Date; | |
public class Server { | |
public static void main(String[] args) throws IOException { | |
//Wait on port | |
try (ServerSocket listener = new ServerSocket(1090)) { | |
//The server is up | |
System.out.println("The server is running..."); | |
//inifite loop | |
while (true) { | |
//Wait for a connection from client | |
try (Socket socket = | |
listener.accept()) { | |
//link output to the socket | |
PrintWriter out = | |
new PrintWriter(socket.getOutputStream(), true); | |
//send something to the client | |
out.println(new Date().toString()); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment