Multiplayer game in Java. Connect client (player) to game that was created by other client

前端 未结 2 2082
时光说笑
时光说笑 2020-12-18 18:08

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 an

相关标签:
2条回答
  • 2020-12-18 18:13

    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 Creating a Multiplayer game in python, 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)
                {
    
                }
            }
        }
    }
    

    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:

    • https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html

    • https://docs.oracle.com/javase/tutorial/networking/sockets/

    • http://www.oracle.com/technetwork/java/socket-140484.html

    • You need a multithreaded server for handle many different connections.

    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:

    • Creating a Multiplayer game in python

    • Xcode Mass Multiplayer (Not What You're Probably Thinking)

    • How would an MMO deal with calculating and sending packets for thousands of players every tick for a live action game?

    0 讨论(0)
  • 2020-12-18 18:39

    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.

    0 讨论(0)
提交回复
热议问题