1

I am working on multiplayer game and I cant to find out how can I connect other clients to the created game. I mean that client A create a socket connection to the server and how other clients (A,B...) can connect to the client A? Can somebody help me please?

P.S. I'm new with network programming, so if you can attach some example i would be very grateful.

Richard H.
  • 33
  • 1
  • 1
  • 6
  • 1
    The question is a bit broad and open ended for StackOverflow. Many good examples of using `Socket` and `ServerSocket` can be found online. A quick search turned up what looks to be a good example http://kodejava.org/how-do-i-create-a-client-server-socket-communication/ – ug_ Apr 09 '15 at 18:01
  • I mean somtehing like that: Player create a game, waiting for other players. And now I don't know how to do that the othe players can join to that game. If I must save the IP of player and on that IP the others will be connected or...I don't know. I realy have no idea how can I do that – Richard H. Apr 09 '15 at 18:18
  • I think the saying goes "You must learn to crawl before you can walk". Start with something small, build on it. Your first attempt wont be perfect it may not even be good. Learn from it and build on it. Sockets and network connections are intermediate topics at best. – ug_ Apr 09 '15 at 18:45

2 Answers2

5

Another client cannot be connected to the Client A because of his firewall.

You can create two majors kinds of network:

  • Server-Client

  • Peer-to-Peer

But a client can save some data to the server and the server can send them to all the clients (you don't need a Peer-to-Peer network for allow the Client B to send some data to the Client A).

Example: The Client B send his map position to the server, the server send the data to all the clients, so the Client A is able to draw a character tileset at the position of the Client B.

For connect two PCs together, you need to forward a port from the modem of your server to the PC used as server, and open the port from the firewall of the PC used as server.

You can also take a look here https://stackoverflow.com/questions/30227722/creating-a-multiplayer-game-in-python/30228185#30228185, I give an example where the clients was able to connect them together with IRC and play at a Tic-Tac-Toe game (so you didn't have to manage a server). I have add an example in Java at the end of this post.

A simple server example:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;


public class Server
{
    public static void main(String[] args) throws Exception
    {
        ServerSocket listener = new ServerSocket(4000);
        String line;
        try
        {
            while (true)
            {
                Socket socket = listener.accept();
                BufferedReader readerChannel = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter writerChannel = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                try
                {
                    writerChannel.write(new Date().toString() + "\n\r");
                    writerChannel.flush();

                    while ((line = readerChannel.readLine()) != null)
                    {
                        System.out.println(line);
                    }
                }
                finally
                {
                    socket.close();
                }
            }
        }
        finally
        {
            listener.close();
        }
    }
}

A simple client example:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;


public class Client
{
    public static void main(String[] args) throws Exception
    {
        Socket socket = new Socket("127.0.0.1", 4000);
        BufferedWriter writerChannel = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        BufferedReader readerChannel = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        
        writerChannel.write(new Date().toString() + "\n\r");
        writerChannel.flush();
        
        while ((line = readerChannel.readLine()) != null)
        {
            System.out.println(line);
        }
    }
}

Also take a look at:

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;


public class Client
{
    public static void main(String[] args) throws Exception
    {
        SSLSocketFactory socketBuilder = (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket socket = (SSLSocket) socketBuilder.createSocket("127.0.0.1", 4000);
    }
}

A simple IRC example:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;


public class Client
{
    public static void main(String[] args) throws Exception
    {
        SSLSocketFactory socketBuilder = (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket socket = (SSLSocket) socketBuilder.createSocket("irc.freenode.net", 6697);
        BufferedWriter writerChannel = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        BufferedReader readerChannel = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        
        String line, computerName, nick, login, channel = "#bot", channelPassword = "";
        long id = 1;
        
        computerName = java.net.InetAddress.getLocalHost().getHostName();
        nick = computerName + "_" + id;
        login = computerName + "_" + id;
        writerChannel.write("NICK " + nick + "\r\n"); // Join IRC with a specific Nick
        writerChannel.write("USER " + login + " 8 * :" + login + " \r\n"); // Join IRC with a specific User
        writerChannel.flush();
        
        while ((line = readerChannel.readLine()) != null)
        {
            if (line.indexOf("004") != -1) // If connected
            {
                break;
            }
            else if (line.indexOf("433") != -1) // If Nick already in use
            {
                id++;
                nick = computerName + "_" + id;
                login = computerName + "_" + id;
                writerChannel.write("NICK " + nick + "\r\n");
                writerChannel.write("USER " + login + " 8 * :" + login + " \r\n");
                writerChannel.flush();
            }
        }
        
        writerChannel.write("JOIN " + channel + " " + channelPassword + "\r\n"); // Join a channel
        writerChannel.flush();
        
        while ((line = readerChannel.readLine()) != null)
        {
            try
            {
                line = line.substring(line.indexOf("#"));
                channel = line.substring(0, line.indexOf(" "));
                
                if (line.toLowerCase().startsWith("ping")) // avoid ping time-out
                {
                    writerChannel.write("PONG :" + line.substring(5) + "\r\n");
                    writerChannel.flush();
                }
                else if (line.toLowerCase().contains("!ping"))
                {
                    writerChannel.write("PRIVMSG " + channel + " :pong\r\n");
                    writerChannel.flush();
                }
                else if (line.toLowerCase().contains("!join"))
                {
                    String newChannel = line.substring(line.indexOf("!join") + 6);
                    int stringPosition;
                    if ((stringPosition = newChannel.indexOf(" ")) != -1)
                    {
                        String newPassword = newChannel.substring(stringPosition + 1);
                        newChannel = newChannel.substring(0, stringPosition);
                        writerChannel.write("JOIN " + newChannel + " " + newPassword + "\r\n");
                        writerChannel.flush();
                    }
                    else
                    {
                        writerChannel.write("JOIN " + newChannel + "\r\n");
                        writerChannel.flush();
                    }
                }
                else if (line.toLowerCase().contains("!leave"))
                {
                    writerChannel.write("PART " + channel + "\r\n");
                    writerChannel.flush();
                }
                else if (line.toLowerCase().contains("!quit"))
                {
                    writerChannel.write("QUIT\r\n");
                    writerChannel.flush();
                    System.exit(0);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

I cannot give you an example for a Peer-to-Peer network because I have never do it. This is really difficult and you have to do a lot of research on internet.

More informations:

Hint - I have already answer at some similar questions. Even if the programming language are sometime different, I give you the link, the logic is always the same so it can maybe help you:

gtiwari333
  • 24,554
  • 15
  • 75
  • 102
tirz
  • 2,041
  • 1
  • 22
  • 37
0

Here is one way to handle it. When a player wants to create a game, his copy of the application should open a ServerSocket on a known port - a port number that the application knows - and maybe display to the player the IP address that the socket was opened on.

Then when another player wants to join a game, she should enter that same IP address and her copy of the application should connect using a regular client Socket, the IP address entered, and the known port that the application knows.

Check the Socket and ServerSocket javadoc for details.

Warren Dew
  • 8,790
  • 3
  • 30
  • 44