Skip to content

Instantly share code, notes, and snippets.

@Eyad-Bereh
Last active June 26, 2020 18:37
Show Gist options
  • Save Eyad-Bereh/619500edc56d51a25ef184465c7f3325 to your computer and use it in GitHub Desktop.
Save Eyad-Bereh/619500edc56d51a25ef184465c7f3325 to your computer and use it in GitHub Desktop.
Using the thread per connection, write a server in Java that echo any received message along with IP addresses and port number of the client.
package app;
import java.net.ServerSocket;
import java.net.Socket;
public class App {
public static void main(String[] args) throws Exception {
try (ServerSocket server = new ServerSocket(49512)) {
while (true) {
try {
Socket clientSocket = server.accept();
EchoServer es = new EchoServer(clientSocket);
Thread client = new Thread(es);
client.start();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
package app;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class AppClient {
public static void main(String[] args) throws Exception {
Socket client = new Socket("127.0.0.1", 49512);
InputStream is = client.getInputStream();
OutputStream os = client.getOutputStream();
Scanner in = new Scanner(System.in);
while (true) {
String line = in.nextLine();
byte[] bytes = new byte[512];
os.write(line.getBytes());
os.flush();
is.read(bytes);
System.out.println(new String(bytes));
System.out.println("------------------------------");
}
}
}
package app;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class EchoServer implements Runnable {
private Socket clientSocket;
public EchoServer(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
while (true) { // هي مالها ضرورية, بس مشان إذا الكلاينت ضل عم يبعت
try {
DataInputStream is = new DataInputStream(this.clientSocket.getInputStream());
DataOutputStream os = new DataOutputStream(this.clientSocket.getOutputStream());
byte[] bytes = new byte[256];
is.read(bytes);
String ipAddress = this.clientSocket.getInetAddress().getHostAddress();
int port = this.clientSocket.getPort();
String message = new String(bytes);
StringBuilder sb = new StringBuilder();
sb.append(ipAddress);
sb.append(";");
sb.append(port);
sb.append(";");
sb.append(message);
os.write(sb.toString().getBytes());
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment