Last active
April 2, 2024 11:35
-
-
Save Anass-ABEA/e9cea5f50e96f3b24a53fb27110668fe to your computer and use it in GitHub Desktop.
Java Sockets #1 : Simplified Client/Server Application
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
package net.sockets.simplified; | |
import java.io.DataOutputStream; | |
import java.io.IOException; | |
import java.net.Socket; | |
import java.util.Scanner; | |
public class Client { | |
private Socket socket; | |
private DataOutputStream out; | |
private Scanner in; | |
public Client(){ | |
try{ | |
socket = new Socket("127.0.0.1", Server.PORT); | |
out = new DataOutputStream(socket.getOutputStream()); | |
in = new Scanner(System.in); | |
writeMessages(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
private void writeMessages() throws IOException { | |
String line = ""; | |
while(!line.equals(Server.STOP_STRING)){ | |
line = in.nextLine(); | |
out.writeUTF(line); | |
} | |
close(); | |
} | |
private void close() throws IOException { | |
socket.close(); | |
out.close(); | |
in.close(); | |
} | |
public static void main(String[] args) { | |
new Client(); | |
} | |
} |
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
package net.sockets.simplified; | |
import java.io.BufferedInputStream; | |
import java.io.DataInputStream; | |
import java.io.IOException; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
public class Server { | |
private ServerSocket server; | |
private DataInputStream in; | |
public static final int PORT = 3030; | |
public static final String STOP_STRING = "##"; | |
public Server(){ | |
try{ | |
server = new ServerSocket(PORT); | |
iniConnections(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
private void iniConnections() throws IOException { | |
Socket clientSocket = server.accept(); | |
in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream())); | |
readMessages(); | |
close(); | |
} | |
private void close() throws IOException { | |
in.close(); | |
server.close(); | |
} | |
private void readMessages() throws IOException { | |
String line = ""; | |
while(!line.equals(STOP_STRING)){ | |
line = in.readUTF(); | |
System.out.println(line); | |
} | |
} | |
public static void main(String[] args) { | |
new Server(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment