-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTCPClientServer.java
More file actions
92 lines (76 loc) · 3.06 KB
/
TCPClientServer.java
File metadata and controls
92 lines (76 loc) · 3.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class TCPClientServer {
// Inner class for the TCP Server
static class TCPServer implements Runnable {
private int port;
public TCPServer(int port) {
this.port = port;
}
@Override
public void run() {
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server started on port " + port);
while (true) {
// Accept a client connection
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
// Create input stream to read client messages
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
// Read and print client messages
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: " + inputLine);
}
// Close the client connection
clientSocket.close();
}
} catch (IOException e) {
System.err.println("Error starting server: " + e.getMessage());
}
}
}
// Inner class for the TCP Client
static class TCPClient implements Runnable {
private String hostname;
private int port;
public TCPClient(String hostname, int port) {
this.hostname = hostname;
this.port = port;
}
@Override
public void run() {
try (Socket socket = new Socket(hostname, port)) {
System.out.println("Connected to server");
// Create output stream to send messages to the server
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
String userInput;
// Read user input and send it to the server
while (true) {
System.out.print("Enter message: ");
userInput = scanner.nextLine();
if (userInput.equalsIgnoreCase("exit")) {
break;
}
out.println(userInput);
}
} catch (IOException e) {
System.err.println("Error connecting to server: " + e.getMessage());
}
}
}
public static void main(String[] args) {
int port = 12345; // Port number to listen on
String hostname = "localhost"; // Server hostname
// Start the server in a new thread
new Thread(new TCPServer(port)).start();
// Start the client in a new thread
new Thread(new TCPClient(hostname, port)).start();
}
}