Send message to all connected clients

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

38 Replies - 1848 Views - Last Post: 02 March 2013 - 10:15 AM Rate Topic: ***** 1 Votes

#31 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8329
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Send message to all connected clients

Posted 19 February 2013 - 01:36 PM

So you have your answer.

You need a class to define what your Screen looks like (with all the squares coordinates and color)
This class implements Serializable so objects of that class can be sent over the wire.

Asynchronous Client receive MouseClick and or CursorKey Move from the user and send them to the Server
The Server updates what the screen should look and broadcast that Screen Definition object to all Client
Clients when receiving that object call their repaint() method which calls paint()
paint() draw the screen based on the definition on that screen definition object
Was This Post Helpful? 1
  • +
  • -

#32 curlyfries1999  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 111
  • Joined: 22-December 11

Re: Send message to all connected clients

Posted 19 February 2013 - 01:47 PM

View Postpbl, on 19 February 2013 - 08:36 PM, said:

So you have your answer.

You need a class to define what your Screen looks like (with all the squares coordinates and color)
This class implements Serializable so objects of that class can be sent over the wire.

Asynchronous Client receive MouseClick and or CursorKey Move from the user and send them to the Server
The Server updates what the screen should look and broadcast that Screen Definition object to all Client
Clients when receiving that object call their repaint() method which calls paint()
paint() draw the screen based on the definition on that screen definition object

Thanks a lot. This really helps :D :bananaman:
Was This Post Helpful? 0
  • +
  • -

#33 curlyfries1999  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 111
  • Joined: 22-December 11

Re: Send message to all connected clients

Posted 20 February 2013 - 08:36 AM

I have updated my Client program and it seems to work nicely. I don't know how efficient or reliable it is but here is the code:

Client class:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

	Socket socket = null;
	static ClientThreadReceive ctr = null;
	static ClientThreadSend cts = null;
	String name = null;
	String[] IPParse;
	String IP;
	int port;

	public static void main(String[] args) throws IOException {
		new Client().runClient(args[0], args[1]);
	}

	public void runClient(String name, String IPPort) throws UnknownHostException, IOException {
		IPParse = IPPort.split(":");
		port = Integer.parseInt(IPParse[1]);
		IP = IPParse[0];
		Socket socket = new Socket(IP, port);
		PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
		printWriter.println(name);
		ctr = new ClientThreadReceive(socket, name);
		ctr.start();
		cts = new ClientThreadSend(socket, name);
		cts.start();
	}
}


ClientThreadReceive class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ClientThreadReceive extends Thread {

	private Socket socket;
	private String name;

	public ClientThreadReceive(Socket socket, String name) {
		this.socket = socket;
		this.name = name;
	}

	public void run() {
		try {
			BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			while (true) {
				if (!input.readLine().startsWith(name)) {
					System.out.println(input.readLine());
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}



ClientThreadSend class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientThreadSend extends Thread {

	private Socket socket;
	String name;

	public ClientThreadSend(Socket socket, String name) {
		this.socket = socket;
		this.name = name;
	}

	public void run() {
		try {
			BufferedReader bufferedReaderFromCommandPrompt = new BufferedReader(new InputStreamReader(System.in));
			PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
			while (true) {
				String readerInput = bufferedReaderFromCommandPrompt.readLine();
				printWriter.println(name + ": " + readerInput);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}


Was This Post Helpful? 0
  • +
  • -

#34 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8329
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Send message to all connected clients

Posted 20 February 2013 - 09:59 AM

You don't need a thread for the send... there is no reason fro the send to while(true)
it can be done in the main thread

The Client starts a thread to red the messages from the Server
when a message is received, it calls a method in the main thread to process it
When the user invoke something in the Client gui a message is send to the Server

class Client extends JFrame implements ActionListener {

    Client() {
      ...connect to server get socket
      ...set up GUI
      add(jtextField);

      ClientThread ct = new ClientThread(this, socket);
      ct.start();

      public void actionPerformed(ActionEvent e) {
        // a enter in the JTextField sends its text tro the Server
        printWriter.write(textfield.getText());
      }

      void fromServer(String msg) {
         ... process message from server
      }

   class ClientThread extends Thread {
       Client client;

       ClientThread(Client client, Socket socket) {
             .. save client (my father)
             ... build inoput stream
       }

       public void run() {
           while(true) {
              ... String msg = receive from server
              client.fromServer(msg);
           }



Have fun

P.S.
if it is for a agame better to use ObjectInputStream and ObjectOutputStream will simplify your life a lot and you can switch() on the message type
Was This Post Helpful? 0
  • +
  • -

#35 curlyfries1999  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 111
  • Joined: 22-December 11

Re: Send message to all connected clients

Posted 20 February 2013 - 10:12 AM

View Postpbl, on 20 February 2013 - 04:59 PM, said:

You don't need a thread for the send... there is no reason fro the send to while(true)
it can be done in the main thread

The Client starts a thread to red the messages from the Server
when a message is received, it calls a method in the main thread to process it
When the user invoke something in the Client gui a message is send to the Server

class Client extends JFrame implements ActionListener {

    Client() {
      ...connect to server get socket
      ...set up GUI
      add(jtextField);

      ClientThread ct = new ClientThread(this, socket);
      ct.start();

      public void actionPerformed(ActionEvent e) {
        // a enter in the JTextField sends its text tro the Server
        printWriter.write(textfield.getText());
      }

      void fromServer(String msg) {
         ... process message from server
      }

   class ClientThread extends Thread {
       Client client;

       ClientThread(Client client, Socket socket) {
             .. save client (my father)
             ... build inoput stream
       }

       public void run() {
           while(true) {
              ... String msg = receive from server
              client.fromServer(msg);
           }



Have fun

P.S.
if it is for a agame better to use ObjectInputStream and ObjectOutputStream will simplify your life a lot and you can switch() on the message type


So what's the benifit of using ObjectInputStream and ObjectOutputStream? Does it increase performance?
Was This Post Helpful? 0
  • +
  • -

#36 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8329
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Send message to all connected clients

Posted 20 February 2013 - 10:41 AM

It is not a performance issue it is to simplify a lot your coding

Extracted from

http://www.dreaminco...r-gui-optional/

Quote

The ChatMessage class.

When you establish connections over TCP it is only a serie of bytes that are actually sent over the wire. If you have a Java application that talks to a C++ application you need to send series of bytes and have both the sender and the receiver to agree on what these bytes represent.

When talking between two Java applications, if both have access to the same code, I personally prefer to send Java Object between the two applications. Actually it will still a stream of bytes that will be sent over the internet but Java will do the job of serializing and deserializing the Java objects for you. To do that you have to create an ObjectInputStream and an ObjectOutputStream from the Socket InputStream and the Socket OutputStream.

The objects sent of the sockets have to implements Serializable.
In this application, all the messages sent from the Server to the Client are String objects. All the messages sent from the Client to the Server (but the first one which is a String) are ChatMessage. ChatMessage have a type and a String that contains the actual message.

ChatMessage.java
import java.io.*;
/*
 * This class defines the different type of messages that will be exchanged between the
 * Clients and the Server. 
 * When talking from a Java Client to a Java Server a lot easier to pass Java objects, no 
 * need to count bytes or to wait for a line feed at the end of the frame
 */
public class ChatMessage implements Serializable {

	protected static final long serialVersionUID = 1112122200L;

	// The different types of message sent by the Client
	// WHOISIN to receive the list of the users connected
	// MESSAGE an ordinary message
	// LOGOUT to disconnect from the Server
	static final int WHOISIN = 0, MESSAGE = 1, LOGOUT = 2;
	private int type;
	private String message;
	
	// constructor
	ChatMessage(int type, String message) {
		this.type = type;
		this.message = message;
	}
	
	// getters
	int getType() {
		return type;
	}
	String getMessage() {
		return message;
	}
}




So you receive always the same ChatMessage object and you can switch(on its type)

ost of the time your server will broadcast to all clients the state of the game.
If that game state is contain in a GameState object it is a lot simpler to simply ship that object over the wire.
Was This Post Helpful? 0
  • +
  • -

#37 RJCoder8989  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 02-March 13

Re: Send message to all connected clients

Posted 02 March 2013 - 12:33 AM

View Postcurlyfries1999, on 17 February 2013 - 12:04 PM, said:

View Postg00se, on 17 February 2013 - 11:59 AM, said:

I am getting the same problem when sending message from it is not going to all server. Please help





import java.io.*;
import java.net.*;


public class ServerChat implements Runnable
{
static ServerSocket server;
static Socket client;

static class Read implements Runnable
{
public void run()
{
try
{
InputStream istream=client.getInputStream();
InputStreamReader isreader=new InputStreamReader(istream);
BufferedReader breader=new BufferedReader(isreader);
String reader;
while((reader=breader.readLine())!=null)
{
System.out.println("From Client:"+reader);
}
breader.close();
istream.close();
isreader.close();
client.close();
}
catch(Exception read)
{
System.out.println(read);
}
}
}

static class Write implements Runnable
{
public void run()
{
try
{
OutputStream opstream=client.getOutputStream();
PrintStream pstream=new PrintStream(opstream);
BufferedReader breader1=new BufferedReader(new InputStreamReader(System.in));
String write;
while(!(write=breader1.readLine()).equals("exit"))
{
pstream.println(write);
}
breader1.close();
opstream.close();
pstream.close();
client.close();
}
catch(Exception write)
{
System.out.println(write);
}
}
}

int n=1;
public void run()
{
for(;;)
{
try
{
Read read=new Read();
Write write=new Write();
client=server.accept();
System.out.println("Connection established from client:"+n);
Thread t1=new Thread(read);
Thread t2=new Thread(write);
t1.start();
t2.start();
}
catch(Exception e)
{
System.out.println(e);
}
n++;
}
}

public static void main(String[] args)throws Exception
{
ServerChat chat=new ServerChat();
server=new ServerSocket(6666);
System.out.println("Waiting for connection");
Thread clientthread=new Thread(chat);
Thread clientthread1=new Thread(chat);
clientthread.start();
clientthread1.start();
}
}
:D/>


I am getting same problem
Was This Post Helpful? 0
  • +
  • -

#38 RJCoder8989  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 02-March 13

Re: Send message to all connected clients

Posted 02 March 2013 - 12:41 AM

View PostRJCoder8989, on 02 March 2013 - 12:33 AM, said:

View Postcurlyfries1999, on 17 February 2013 - 12:04 PM, said:

View Postg00se, on 17 February 2013 - 11:59 AM, said:

I am getting the same problem when sending message from server it is not going to all clients. Please help


:D/>/>
import java.io.*;
import java.net.*;


public class ServerChat implements Runnable
{
    static ServerSocket server;
    static Socket client;

    static class Read implements Runnable
    {
        public void run()
        {
            try
            {
                InputStream istream=client.getInputStream();
                InputStreamReader isreader=new InputStreamReader(istream);
                BufferedReader breader=new BufferedReader(isreader);
                String reader;
                while((reader=breader.readLine())!=null)
                {
                    System.out.println("From Client:"+reader);
                }
                breader.close();
                istream.close();
                isreader.close();
                client.close();
            }
            catch(Exception read)
            {
                System.out.println(read);
            }
        }
    }

    static class Write implements Runnable
    {
            public void run()
            {
                try
                {
                    OutputStream opstream=client.getOutputStream();
                    PrintStream pstream=new PrintStream(opstream);
                    BufferedReader breader1=new BufferedReader(new InputStreamReader(System.in));
                    String write;
                    while(!(write=breader1.readLine()).equals("exit"))
                    {
                        pstream.println(write);
                    }
                    breader1.close();
                    opstream.close();
                    pstream.close();
                    client.close();
                }
                catch(Exception write)
                {
                    System.out.println(write);
                }
            }
    }

    int n=1;
    public void run()
    {
        for(;;)/>/>
        {
            try
            {
                Read read=new Read();
                Write write=new Write();
                client=server.accept();
                System.out.println("Connection established from client:"+n);
                Thread t1=new Thread(read);
                Thread t2=new Thread(write);
                t1.start();
                t2.start();
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
          n++;
        }
    }

    public static void main(String[] args)throws Exception
    {
        ServerChat chat=new ServerChat();
        server=new ServerSocket(6666);
        System.out.println("Waiting for connection");
        Thread clientthread=new Thread(chat);
        Thread clientthread1=new Thread(chat);
        clientthread.start();
        clientthread1.start();
    }
}



Was This Post Helpful? 0
  • +
  • -

#39 curlyfries1999  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 111
  • Joined: 22-December 11

Re: Send message to all connected clients

Posted 02 March 2013 - 10:15 AM

View PostRJCoder8989, on 02 March 2013 - 07:41 AM, said:

View PostRJCoder8989, on 02 March 2013 - 12:33 AM, said:

View Postcurlyfries1999, on 17 February 2013 - 12:04 PM, said:

View Postg00se, on 17 February 2013 - 11:59 AM, said:

I am getting the same problem when sending message from server it is not going to all clients. Please help


:D/>/>/>
import java.io.*;
import java.net.*;


public class ServerChat implements Runnable
{
    static ServerSocket server;
    static Socket client;

    static class Read implements Runnable
    {
        public void run()
        {
            try
            {
                InputStream istream=client.getInputStream();
                InputStreamReader isreader=new InputStreamReader(istream);
                BufferedReader breader=new BufferedReader(isreader);
                String reader;
                while((reader=breader.readLine())!=null)
                {
                    System.out.println("From Client:"+reader);
                }
                breader.close();
                istream.close();
                isreader.close();
                client.close();
            }
            catch(Exception read)
            {
                System.out.println(read);
            }
        }
    }

    static class Write implements Runnable
    {
            public void run()
            {
                try
                {
                    OutputStream opstream=client.getOutputStream();
                    PrintStream pstream=new PrintStream(opstream);
                    BufferedReader breader1=new BufferedReader(new InputStreamReader(System.in));
                    String write;
                    while(!(write=breader1.readLine()).equals("exit"))
                    {
                        pstream.println(write);
                    }
                    breader1.close();
                    opstream.close();
                    pstream.close();
                    client.close();
                }
                catch(Exception write)
                {
                    System.out.println(write);
                }
            }
    }

    int n=1;
    public void run()
    {
        for(;;)/>/>/>
        {
            try
            {
                Read read=new Read();
                Write write=new Write();
                client=server.accept();
                System.out.println("Connection established from client:"+n);
                Thread t1=new Thread(read);
                Thread t2=new Thread(write);
                t1.start();
                t2.start();
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
          n++;
        }
    }

    public static void main(String[] args)throws Exception
    {
        ServerChat chat=new ServerChat();
        server=new ServerSocket(6666);
        System.out.println("Waiting for connection");
        Thread clientthread=new Thread(chat);
        Thread clientthread1=new Thread(chat);
        clientthread.start();
        clientthread1.start();
    }
}




Download my project from GitHub: https://github.com/c...ab=repositories
I think I have fixed the problem. The client is the repository named Game.
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3