Created
April 17, 2022 23:36
-
-
Save Anass-ABEA/2e9519e0dda1fb8a4962f838070c14e6 to your computer and use it in GitHub Desktop.
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.IOException; | |
import java.io.PrintWriter; | |
import java.net.Socket; | |
public class Client { | |
private Socket socket; | |
public void init() throws Exception{ | |
socket = new Socket("127.0.0.1", 4040); | |
System.out.println("Connecting to the server"); | |
} | |
public void sendMessage(String msg) throws Exception{ | |
System.out.println("Sending the message to the server"); | |
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); | |
writer.println(msg); | |
} | |
public void close(){ | |
if(socket != null) { | |
try { | |
socket.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
public static void main(String[] args) { | |
Client client = new Client(); | |
try{ | |
client.init(); | |
client.sendMessage("Hello World"); | |
}catch (Exception ignored){ | |
}finally { | |
client.close(); | |
} | |
} | |
} |
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.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
public class Server { | |
private ServerSocket server; | |
public void initAndStart() throws Exception { | |
server = new ServerSocket(4040); | |
System.out.println("Server is running..."); | |
while (true) { | |
Socket clientSocket = server.accept(); | |
System.out.println("Client is connected"); | |
readMessageFromSocket(clientSocket); | |
} | |
} | |
private void readMessageFromSocket(Socket clientSocket) throws Exception { | |
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); | |
for (int chr = reader.read(); reader.ready(); chr = reader.read()) { | |
System.out.print( (char) chr); | |
} | |
} | |
public void close(){ | |
if(server != null) { | |
try { | |
server.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
public static void main(String[] args) { | |
Server server = new Server(); | |
try{ | |
server.initAndStart(); | |
}catch (Exception e){ | |
server.close(); | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment