我可以使用Java中的套接字连接两台计算机吗?

时间:2018-09-29 07:00:28

标签: java sockets networking

是否可以编写客户端服务器代码,以使用Java中的套接字连接两台不同的计算机以玩多人游戏?这些计算机是否需要通过电缆连接?还是可以通过其他来源发送数据? (就像互联网..)或者如果我只知道两台计算机的IP地址并将其放在套接字中就足够了吗?请告诉我我该怎么做。

1 个答案:

答案 0 :(得分:1)

您可以连接同一Wifi网络上的计算机。您将需要打开服务器,然后打开连接到该服务器的客户端。 以下代码可能会有所帮助:

Server.java

    ArrayList<Socket> clientSockets = new ArrayList<>();
    try {
            ServerSocket serverSocket = new ServerSocket(port); // port same as client
            InetAddress inetAddress = InetAddress.getLocalHost();
            System.out.println("Server opened at: "+inetAddress.getHostAddress());

            while (true) // this keeps the server listening
            {
                final Socket socket = serverSocket.accept(); // this accepts incomming connections
                clientSockets.add(socket); // adds current connection to an arraylist
                System.out.println(timestamp()+"Connection from "+socket.getInetAddress());
                    Thread t = new Thread(new Runnable() // Thread handles messages sent by client that just connected
                    {
                    @Override
                    public void run() {
                        try
                        {
                            while (socket.isConnected())
                            {
                                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                String fromClient = br.readLine();
                                if (fromClient != null)
                                {
                                 //use message from client
                                }
                                else // connection might have been reset by client
                                    {
                                        socket.close();
                                        clientSockets.remove(socket);
                                    }
                            }
                        } catch (SocketException e)
                        {
                          System.out.println("Disconnection from "+socket.getInetAddress());
                        } catch (IOException e) {}
                    }
                });
                t.start();
            }
            } catch (Exception e) {}

Client.java-添加两个按钮,一个用于连接,另一个用于发送

bConnect.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
                try {
                        InetAddress address = InetAddress.getByName(host); // host IPaddress
                        socket = new Socket(address, port); // port same as server
                        bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

                        final Timer time = new Timer(); // to get new server txt if it changes
                        TimerTask t = new TimerTask() {
                            @Override
                            public void run() {
                                try {
                                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                    String kry = br.readLine(); 
                                // use message from server
                                } catch (Exception e1) {
                                    JOptionPane.showMessageDialog(null, "The Server has just gone offline");
                                }
                            }
                        };
                        time.scheduleAtFixedRate(t, 0, 2000);
                }
                catch (Exception e1)
                {e1.printStackTrace();
                    JOptionPane.showMessageDialog(null, "The Server is not online");}
        }
    });



bSend.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String textGekry = "what you are sending";
            if (!textGekry.equals(""))
            {
                String sendMessage = textGekry + "\n";
                try
                {
                    bw.write(sendMessage);
                    bw.flush();
                }
                catch (Exception e1)
                {
                    JOptionPane.showMessageDialog(null,"The Server is most likely offline");
                }
            }
        }
    });