------------------------------------------
import java.io.*;
import java.net.*;
public class MyChatServer {
public static void main(String args[]) {
try {
// Create a new server socket that listens at a port
ServerSocket ss = new ServerSocket(Write your port number here);
System.out.println("Server is lisenting ... ");
Socket skt = ss.accept();//accept a connection from client on the port
OutputStream os = skt.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
InputStream is = skt.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String rcv_msg, send_msg;
while(true) {
// Recieve a message from client
System.out.println("Waiting for client to respond ... ");
if((rcv_msg = (String)ois.readObject()) != null) {
//(String)ois.readObject() is substituted to rcv_msg,
//which means rcv_msg is the received message from the client System.out.println("From Client : " + rcv_msg); } // Send a message to client System.out.print("\nTo Client : "); send_msg = br.readLine(); //Accepting command line argument oos.writeObject(send_msg); //Sending the message which is named as "send_msg" } } catch(Exception e) { System.out.println(e); } } }
------------------------------------------//which means rcv_msg is the received message from the client System.out.println("From Client : " + rcv_msg); } // Send a message to client System.out.print("\nTo Client : "); send_msg = br.readLine(); //Accepting command line argument oos.writeObject(send_msg); //Sending the message which is named as "send_msg" } } catch(Exception e) { System.out.println(e); } } }
References
csegeeks.com "Network Programming with Java" Java tutorial, retrieved on 23rd November 2015