Compare commits

...

3 Commits

Author SHA1 Message Date
andrzej d4572677f5 working multi client 2024-11-12 10:13:53 +01:00
andrzej 53c846a386 client 2024-11-12 09:56:25 +01:00
andrzej b0fcb7c79c server 2024-11-12 09:55:12 +01:00
5 changed files with 119 additions and 0 deletions

BIN
Client.class Normal file

Binary file not shown.

47
Client.java Normal file
View File

@ -0,0 +1,47 @@
import java.io.*;
import java.net.*;
import java.util.*;
// Client class
class Client {
// driver code
public static void main(String[] args) {
// establish a connection by providing host and port
// number
try (Socket socket = new Socket("localhost", 8080)) {
// writing to server
PrintWriter out = new PrintWriter(
socket.getOutputStream(), true);
// reading from server
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// object of scanner class
Scanner sc = new Scanner(System.in);
String line = null;
while (!"exit".equalsIgnoreCase(line)) {
// reading from user
line = sc.nextLine();
// sending the user input to server
out.println(line);
out.flush();
// displaying server reply
System.out.println("Server replied "
+ in.readLine());
}
// closing the scanner object
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

BIN
Server$ClientHandler.class Normal file

Binary file not shown.

BIN
Server.class Normal file

Binary file not shown.

72
Server.java Normal file
View File

@ -0,0 +1,72 @@
import java.io.*;
import java.net.*;
class Server {
public static void main(String[] args) {
ServerSocket server = null;
try {
// start server
server = new ServerSocket(8080);
server.setReuseAddress(true);
while (true) {
Socket client = server.accept();
System.out.println("New client: " + client.getInetAddress().getHostAddress());
ClientHandler clientSock = new ClientHandler(client);
new Thread(clientSock).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static class ClientHandler implements Runnable {
private Socket clientSocket;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
public void run() {
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.printf("From the client: %s\n", line);
out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
System.out.println("closing socket " + clientSocket.getInetAddress().getHostAddress());
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}