Category: Java

How to Create a TCP Client Server Socket example using Java

*****************************TCPSERVER***********************

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

class TCPServer {
 public static void main(String argv[]) throws Exception {
 ServerSocket ourFirstSocket = new ServerSocket(port);
 while (true) {

Socket connectionSocket = ourFirstSocket.accept();
 BufferedReader messagesFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
 String clientSentence = messagesFromClient.readLine();
 System.out.println("Received: " + clientSentence);
 }
 }
}

*****************************TCPCLIENT***********************

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.*;
class TCPClient {
public static void main(String agrs[]) throws Exception {
Socket clientsocket = new Socket("localhost", port);
DataOutputStream outToServer = new DataOutputStream(clientsocket.getOutputStream());
BufferedReader infromUser = new BufferedReader(new InputStreamReader(System.in));
String sentence = //infromUser.readLine();
outToServer.writeBytes(sentence + '\n');

clientsocket.close();
}
}