Skip to content

Instantly share code, notes, and snippets.

@roshanadh
Created April 10, 2019 06:54
Show Gist options
  • Save roshanadh/6a9ec13b9b5ead4d69118d41bada00dc to your computer and use it in GitHub Desktop.
Save roshanadh/6a9ec13b9b5ead4d69118d41bada00dc to your computer and use it in GitHub Desktop.
Receive messages from client in Java
/* Server Program */
import java.io.*;
import java.net.*;
public class TCPServer
{
public static void main(String []args) throws Exception
{
String clientData, processedData;
/* Creating a Server Socket for Server */
ServerSocket welcomeSocket=new ServerSocket(2222);
System.out.println("Waiting for Client..");
while(true)
{
/* Listening to the Client Request */
Socket connectionSocket=welcomeSocket.accept();
/* Creating Input Stream for the Server */
BufferedReader inFromClient=new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
/* Creating Output Stream for the Client */
DataOutputStream outToClient=new DataOutputStream(connectionSocket.getOutputStream());
clientData=inFromClient.readLine();
System.out.println("From Client: "+clientData);
processedData="ACKNOWLEDGEMENT for '"+clientData+"' from Client.\n";
/* Sending Acknowledgement Message to the Client */
outToClient.writeBytes(processedData);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment