Java - 套接字服务器刷新

时间:2014-06-08 19:18:44

标签: java sockets client-server lan

我正在创建一个局域网游戏,我希望我的服务器和客户端能够一遍又一遍地进行通信,例如玩家的坐标。我有一个非常简单的服务器,客户端设置在这里是代码:

public class SimpleClient {

    public SimpleClient(){

        String host = "192.168.1.121";
        int port;

        if(host.length() == 0){
            host = "192.168.1.121";
            port = 9999;
        } else {
            host = "localhost";
            String portStr = "9999";
            try {
                port = Integer.parseInt(portStr);
            } catch(Exception e){
                port = 9999;
            }
        }

        try {
            System.out.println("Client is tying to connect to the server host: " + host + " " + port);
            Socket skt = new Socket(host,port);

            BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            PrintStream myOutput = new PrintStream(skt.getOutputStream());

            myOutput.print("Hello Server!\n");

            String buf = myInput.readLine();
            if(buf != null) {
                System.out.println("Client recived [" + buf + "] from the sever");
            }

        } catch(IOException e){
            e.printStackTrace();
        }


    }

这是服务器:

public void SimpleServer(){

        try {

            ServerSocket myServerSocket = new ServerSocket(9999);

            System.out.println("Server is waiting for an incoming connection on host=" + InetAddress.getLocalHost().getHostAddress()
                                + " port=" + myServerSocket.getLocalPort());
            Socket skt = myServerSocket.accept();

            BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            PrintStream myOutput = new PrintStream(skt.getOutputStream());

            String buf = myInput.readLine();

            myOutput.print("Hello Client!\n");
            myOutput.print("Hello Client!\n");
            myOutput.print("Hello Client!\n");


            if(buf != null){
                System.out.println("Ther Server read: [" + buf + "]");
                myOutput.print("got it!");
            }


        }catch(Exception e){

        }

    }

我再次尝试让服务器和客户端一遍又一遍地发送对方的消息。我已经尝试了一个while循环,它冻结了游戏。感谢。

0 个答案:

没有答案