Search code examples
javaserversocket

Message passing in Server Socket in Java


I am new in Socket programming of java, i had written two files in Java named Server.java and Client.java as below:

Server.java

import java.io.*;
import java.net.*;
public class Server
{
 static ServerSocket server = null;
 static Socket socket = null;
 static int userConnected=0;
 static String msg = "In Server";
 public static void main(String []args)throws Exception
 {
    int port = 1234;
    server = new ServerSocket(port);
    PrintStream output = null;
    while(true)
    {
        socket=server.accept();
        //Connection Arrived
        userConnected++;
        System.out.println("A new user arrived,\nNo. of user connected "+(userConnected));
    }
 } 
}

Client.java

import java.net.*;
import java.io.*;
public class Client
{
    static Socket socket = null;
    public static void main(String[] args) throws Exception
    {
        socket = new Socket("localhost",1234);
    }
}

When running Server class file on one system it will create Server on Port 1234 and when i run client class file it get successfully connected to Server on port 1234 and when i run another Client class file by another Console it also get connected to Server on port 1234,

What i want is to perform message passing between these two clients i.e. the message written in first client get shown in second client and vise-versa.

Can anyone please help me ??


Solution

  • http://www.tutorialspoint.com/java/java_networking.htm

    I suggest you take a look at this. You can take a horse to the water, but cannot make it drink!