3

我正在尝试使用 Java 将一些数据从客户端发送到服务器,这是我的 PlayerThread,它在新客户端连接时在服务器上运行

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        //Create a link to send data to the server
        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                socket.getInputStream()));
        while(true)
        {
            out.println(pongData);
            String temp = in.readLine();
            if(temp == "up")
            {
                System.out.println("Up you say");
            }
        }
//There is a little more but no point to give it all

行 String temp = in.readLine(); 当客户端断开连接时给我这个错误

java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Pong.PongPlayerThread.run(PongPlayerThread.java:36)

这是客户端代码

try
    {
        socket = new Socket(host, port);
        serverOut = new PrintWriter(socket.getOutputStream(), true);
        serverInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
    catch (UnknownHostException e)
    {
        System.err.println("Couold not connect to host:" + host);
        System.exit(1);
    }
    catch (IOException e)
    {
        System.err.println("Could not get Input/Output from server");
        System.exit(1);
    }

    System.out.println("Connected to Server");

    while ((pos = serverInput.readLine()) != null) 
    {
        String[] posValues = pos.split(":");
        model.getBall().setX(Double.parseDouble(posValues[0]));
        model.getBall().setY(Double.parseDouble(posValues[1]));

        if(PongController.moveUp == true)
        {
            serverOut.println("up");
            PongController.moveUp = false;
        }

        //If the client presses up or down arrow, a message will be sent to the server
        //the server will then update the movement and the clients will be able to see it

    }

这段代码有效,但它似乎根本没有真正发送消息:(,如果有人能帮助我,那就太棒了

帆布

我刚刚编辑了一些代码,我发现在 PlayerThread 中的行

if(temp.equals("up"))
            {
                System.out.println("Up you say");
            }

是问题所在,我在客户端的流一开始就设置为空,这可能是问题吗?发送空?

这是更新版本

    while ((pos = serverInput.readLine()) != null) 
    {
        String[] posValues = pos.split(":");
        model.getBall().setX(Double.parseDouble(posValues[0]));
        model.getBall().setY(Double.parseDouble(posValues[1]));
        serverOut.println("nothing");

        if(PongController.moveUp == true)
        {
            System.out.println("Up");
            serverOut.println("up");
            PongController.moveUp = false;
        }
        else
        {
            serverOut.println("nothing");
        }

    }

但我仍然遇到同样的错误

检查 in.readLine 是否等于我在这里得到的任何东西是代码

try
    {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
         BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    socket.getInputStream()));

         System.out.println("Checking readLine value");

         if(in.readLine() == null)
         {
             System.out.println("A ok");
         }
         else
         {
             System.out.println(":" + in.readLine());
         }

        while(true)
        {
             String temp = in.readLine();
             if(temp == "up")
             {
                    System.out.println("Up you say");
             }
            out.println(pongData);
        }
    }
    catch (IOException e) 
    {
        e.printStackTrace();
    }

这是结果

Pong
400.0:301.0:60.0:300.0:740.0:300.0
Server started
Server was setup and will try to create a socket
Data sent
Checking readLine value
Connection reset, and then followed by lots of red lines

我还可以做些什么?

我只是想像这样检查我的 BufferedReader

BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    socket.getInputStream()));

        System.out.println(in.toString());
        System.out.println(in.readLine());

我为 in.toString 获得 java.io.BufferedReader@6262937c 但对于 readLine 我再次重置连接...

快速更新,

在我的客户代码中,如果我有这个

 while ((pos = serverInput.readLine()) != null) 
    {
        String[] posValues = pos.split(":");
        model.getBall().setX(Double.parseDouble(posValues[0]));
        model.getBall().setY(Double.parseDouble(posValues[1]));
        serverOut.println("nothing"); //<---

客户端将连接,获取乒乓球的位置,但随后它将停止从服务器接收数据并自行移动球(尚未禁用更新方法)。serverOut 是

serverOut = new PrintWriter(socket.getOutputStream(), true);
4

2 回答 2

8

好的,所以我注意到您最近一直在问很多有关网络的问题,我想您可能需要一些基础知识方面的帮助。这是一个非常简单的服务器:

package com;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleServer implements Runnable
{    
    public SimpleServer()
    {
        started = false;
        serverSocket = null;
    }

    public void start()
    {
        if(!started)
        {
            started = true;

            try
            {
                serverSocket = new ServerSocket(PORT);
                running = true;

                serverThread = new Thread(this);
                serverThread.start();

                System.out.println("Server started!\n");
            }catch(Exception e)
            {
                e.printStackTrace();
                System.exit(0);
            }
        }
    }

    public void stop()
    {
        running = false;
        started = false;

        if(serverThread != null)
            serverThread.interrupt();
        serverThread = null;
    }

    public void run()
    {
        try
        {
            while(running)
            {
                try
                {
                    Socket client = serverSocket.accept();
                    System.out.println("Client Accepted!");

                    ClientHandler handler = new ClientHandler(client);

                    handler.sendMessage("Hello, SimpleClient!");
                    System.out.println("Sendeing client a message...");
                }catch(Exception e){e.printStackTrace();}
            }
        }catch(Exception e){e.printStackTrace();}
    }

    private boolean started;
    private boolean running;
    private ServerSocket serverSocket;
    private Thread serverThread;

    private static final int PORT = 8081;

    public static void main(String args[])
    {
        SimpleServer server = new SimpleServer();
        server.start();
    }

    public class ClientHandler implements Runnable
    {
        public ClientHandler(Socket socket)
        {
            this.socket = socket;

            try
            {
                writer = new PrintWriter(socket.getOutputStream());
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                running = true;

                runningThread = new Thread(this);
                runningThread.start();
            }catch(Exception e){e.printStackTrace(); disconnect();}
        }

        public void disconnect()
        {
            running = false;
            if(runningThread != null)
                runningThread.interrupt();
            runningThread = null;

            try
            {
                reader.close();
            }catch(Exception e){}
            reader = null;

            try
            {
                writer.close();
            }catch(Exception e){}
            writer = null;
            try
            {
                socket.close();
            }catch(Exception e){}
            socket = null;
        }

        public void sendMessage(String message)
        {
            if(running)
            {
                writer.println(message);
                writer.flush();
            }
        }

        public void run()
        {
            try
            {
                String message = "";
                while((message = reader.readLine()) != null && running)
                {
                    System.out.println("Message Recieved: " + message);
                }
            }catch(Exception e){e.printStackTrace(); disconnect();}
        }

        private Socket socket;
        private PrintWriter writer;
        private BufferedReader reader;

        private Thread runningThread;
        private boolean running;
    }
}

现在这里是客户端:

package com;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SimpleClient implements Runnable
{
    public SimpleClient()
    {
        try
        {
            socket = new Socket("127.0.0.1", PORT);
            writer = new PrintWriter(socket.getOutputStream());
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            running = true;

            runningThread = new Thread(this);
            runningThread.start();
        }catch(Exception e){e.printStackTrace(); disconnect();}
    }

    public void disconnect()
    {
        running = false;
        if(runningThread != null)
            runningThread.interrupt();
        runningThread = null;

        try
        {
            reader.close();
        }catch(Exception e){}
        reader = null;

        try
        {
            writer.close();
        }catch(Exception e){}
        writer = null;
        try
        {
            socket.close();
        }catch(Exception e){}
        socket = null;
    }

    public void sendMessage(String message)
    {
        if(running)
        {
            writer.println(message);
            writer.flush();
        }
    }

    public void run()
    {
        try
        {
            String message = "";
            while((message = reader.readLine()) != null && running)
            {
                System.out.println("Message Recieved: " + message);

                System.out.println("Sending a response!");
                sendMessage("Hello, SimpleServer!");
            }
        }catch(Exception e){e.printStackTrace(); disconnect();}
    }

    private Socket socket;
    private PrintWriter writer;
    private BufferedReader reader;

    private Thread runningThread;
    private boolean running;

    private static final int PORT = 8081;

    public static void main(String args[])
    {
        new SimpleClient();
    }
}

为了在 Java 中制作成功的服务器,您需要实现大量的面向对象。如果服务器不仅要处理侦听客户端,还要处理向这些客户端发送和接收消息,服务器将过于复杂。这就是我通常使用ClientHandler类的原因。这个类处理所有的通信并且很容易实现。客户端和服务器不应该在同一个文件中,因为它们是分开运行的。

如果您不确定服务器和客户端应该如何工作,这也可能会让您感兴趣:

我希望这有帮助!

约翰

于 2013-02-16T19:50:27.643 回答
1

您可能需要刷新输出。

http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html#flush()

于 2013-02-14T17:14:43.640 回答