java tcp server
java tcp server
Here's a basic implementation of a TCP server using Java:
ServerCode.java
import java.net.*;
import java.io.*;
public class ServerCode {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(8000);
System.out.println("Server started. Listening for incoming connections...");
Socket socket = server.accept();
System.out.println("Client connected: " + socket.getInetAddress());
// Input Stream to read from the client
InputStream inStream = socket.getInputStream();
// Output Stream to write to the client
OutputStream outStream = socket.getOutputStream();
// Read and display message from the client
BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
String message;
while ((message = br.readLine()) != null) {
System.out.println("Received: " + message);
// Send response back to the client
PrintWriter pw = new PrintWriter(outStream, true);
pw.println("Server received your message! ");
pw.flush();
}
socket.close();
}
}
Explanation
Create aServerSocket
object and bind it to a specific port (in this case, 8000). The server waits for incoming connections using the accept()
method. When a client connects, get an input stream (InputStream
) and output stream (OutputStream
) from the socket. Read messages from the client using a BufferedReader
object, which reads line by line. For each message received, print it to the console and send a response back to the client using a PrintWriter
object.
Example Client-Server Communication
Client: telnet localhost 8000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello, server!
Server:
Server started. Listening for incoming connections...
Client connected: /127.0.0.1
Received: Hello, server!
Server received your message!
Additional Notes
This implementation assumes a simple text-based communication between the client and server. For more complex protocols or data transfer (e.g., binary files), you would need to handle input/output streams differently. In a real-world scenario, consider using multithreading or asynchronous programming to handle multiple connections simultaneously.Remember to replace localhost
with your actual IP address or hostname if the client is connecting from another machine.
Java tcp example
Here's a basic example of implementing TCP (Transmission Control Protocol) using Java:
Server Side (TCPServer.java)
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("Server is running...");
Socket socket = serverSocket.accept();
System.out.println("Client connected");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Received: " + line);
if (line.equals("exit")) {
break;
}
writer.println(line); // echo back
}
socket.close();
}
}
Client Side (TCPClient.java)
import java.net.*;
import java.io.*;
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8000);
System.out.println("Connected to the server");
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Received: " + line);
if (line.equals("exit")) {
break;
}
writer.println(line); // send back
}
socket.close();
}
}
To run the example:
Compile both files usingjavac
command:
Run the server:javac TCPServer.java
javac TCPClient.java
Run multiple clients (e.g., Java programs, shell scripts, or even other programming languages) by executing the client program on different machines or threads.java TCPServer
This example demonstrates a simple TCP-based communication between a server and one or more clients. The server waits for incoming connections and sends responses back to each connected client. Clients send requests to the server and receive responses.
How it works:
A client initiates a connection request by callingSocket
constructor with the server's IP address (or hostname) and port number. The server accepts the connection using ServerSocket.accept()
method, creating a new socket for that client. Clients send requests to the server using PrintWriter.println()
. The server reads incoming data from each client using BufferedReader.readLine()
and processes it accordingly (in this example, echoing back). Clients receive responses from the server using BufferedReader.readLine()
and process them as needed.
This basic example serves as a starting point for building more complex TCP-based applications, such as web servers, chat services, or file transfer protocols.
Note: These examples are intentionally simplified to focus on the core TCP functionality. In real-world applications, you would need to handle issues like:
Handling multiple concurrent connections Implementing error handling and exception management Managing socket timeouts and disconnections Ensuring secure data transmission using SSL/TLS or other encryption methodsAlways remember to close resources (e.g., sockets) when finished with them to prevent memory leaks!