Last active
April 30, 2019 15:52
-
-
Save Asynchronousx/a2eb2b4ad346b8293a2008ac98053a3b to your computer and use it in GitHub Desktop.
Simple socket communication between a client and a server in Java
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.net.*; | |
| import java.io.*; | |
| import java.util.Scanner; | |
| public class Client { | |
| //In the client, we just need one socket: The socket we'll going to connect with: the one related | |
| //to the server. | |
| private Socket ssock; | |
| //Also, we need a reader and a writer to communicate with the server, and a scanner for the input. | |
| private Scanner keyboard; | |
| private PrintWriter writer; | |
| private BufferedReader reader; | |
| //Flag that take note if a connection was successful | |
| private Boolean connected = false; | |
| //Let's then define a connection and the reader/writer: if the socket creation is successful, | |
| //set the connected flag to true. | |
| public void openConnection(String ip, int port) { | |
| try { | |
| ssock = new Socket(ip, port); | |
| connected = true; | |
| keyboard = new Scanner(System.in); | |
| writer = new PrintWriter(ssock.getOutputStream(), true); | |
| reader = new BufferedReader(new InputStreamReader(ssock.getInputStream())); | |
| } catch (Exception e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| //This function will send a message to the server and receive a response back. | |
| public void sendMessage(String msg) { | |
| //returnMsg is initially error: if not modified, this will mean that something went wrong. | |
| String toSend; | |
| try { | |
| //While the client is still connected, send the echoing string to the server | |
| //and wait for a reply. if the client wants to exit, he need to write "/EXIT". | |
| while (connected) { | |
| //take the string in input | |
| System.out.print("Echo string: "); | |
| toSend = keyboard.nextLine(); | |
| //if the client wants to exit | |
| if(toSend.equals("/EXIT")) { | |
| connected = false; | |
| break; | |
| } | |
| //then send it to the server | |
| writer.println(toSend); | |
| //wait for a response | |
| System.out.println("String received: " + reader.readLine()); | |
| } | |
| } catch (Exception e) { | |
| e.printStackTrace(); | |
| } | |
| System.out.println("Disconnected, exiting.."); | |
| //closing connection | |
| closeConnection(); | |
| } | |
| public void closeConnection() { | |
| //Close all the streams | |
| try { | |
| ssock.close(); | |
| writer.close(); | |
| reader.close(); | |
| } catch (Exception e) { | |
| e.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
| public class Main { | |
| public static void main(String[] args) { | |
| Client client = new Client(); | |
| client.openConnection("YOUR IP", 55000); | |
| client.sendMessage("Hello Server!"); | |
| } | |
| } |
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
| public class Main { | |
| public static void main(String[] args) { | |
| int port = 55000; | |
| Server server = new Server(); | |
| server.openConnection(port); | |
| } | |
| } |
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.net.*; | |
| import java.io.*; | |
| public class Server { | |
| //The server needs two socket: his own, and the one of his client. (Just like C). | |
| //The server got it's own type, Server Sock. The client got a generic Socket. | |
| private ServerSocket ssock; | |
| private Socket csock; | |
| //We need a reader and a writer to write and read onto the socket. | |
| private PrintWriter writer; | |
| private BufferedReader reader; | |
| //Flag that indicates if the client is connected | |
| Boolean connected = false; | |
| public void openConnection(int port) { | |
| //In the standard socket phase, we got 4 phase: socket, bind, accept and connect (Server side). | |
| //In java, we must only define two things: the port on which the server will be listening (with a | |
| //new definition of a ServerSocket) and telling to that socket that he's ready to accept a new connection: | |
| //Just like traditional C networking, once the client got accepted, it will be put into a socket. | |
| try { | |
| //Without specifying any binding, we're simple telling he should accept INADDR_ANY on the port PORT. | |
| this.ssock = new ServerSocket(port); | |
| csock = ssock.accept(); | |
| connected = true; | |
| } catch (Exception e) { | |
| e.printStackTrace(); | |
| } | |
| //Now we need to init the writer and the reader, both of them on the client socket. | |
| //Why both of them? Because we need to both receive something in input and then output | |
| //something to the client. We'll use the stream relative to the client socket to achieve that. | |
| try { | |
| //true means we want to autoflush the byte in the stream. | |
| writer = new PrintWriter(csock.getOutputStream(), true); | |
| reader = new BufferedReader(new InputStreamReader(csock.getInputStream())); | |
| } catch (Exception e) { | |
| e.printStackTrace(); | |
| } | |
| //Now let's communicate | |
| String received; | |
| try { | |
| //Here we're setting up a simple echoing system: while the server is connected to the client, | |
| //receive a string from him and check if the client wants to exit: if the server received | |
| //the string /EXIT, it will break the cycle and do the cleanup operation on the connection. | |
| //if is a normal string, the server will concat "ECHOED" to that and return to the client. | |
| while(connected) { | |
| //reading from the client | |
| received = reader.readLine(); | |
| //checking if the client wanted to exit | |
| if(received.equals("/EXIT")) { | |
| connected = false; | |
| break; | |
| } | |
| //printing what the client said | |
| System.out.println("Client on " + csock.getInetAddress() + " said: " + received); | |
| //if not, just continue talking with the client | |
| received = received.concat("ECHOED"); | |
| writer.println(received); | |
| } | |
| } catch (Exception e) { | |
| e.printStackTrace(); | |
| } | |
| //Close the connection. | |
| System.out.println("Client exited, closing.."); | |
| closeConnection(); | |
| } | |
| public void closeConnection() { | |
| //Close all the streams | |
| try { | |
| ssock.close(); | |
| csock.close(); | |
| writer.close(); | |
| reader.close(); | |
| } catch (Exception e) { | |
| e.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
| Simple Server and Client class to start communicating through socket in Java. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment