BufferedReader给Connection连接重置?

时间:2013-02-14 17:08:20

标签: java networking tcp

我正在尝试使用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);

2 个答案:

答案 0 :(得分:6)

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

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类的原因。该类处理所有通信,并且非常容易实现。客户端和服务器永远不应该在同一个文件中,因为它们应该单独运行。

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

我希望这有帮助!

约翰

答案 1 :(得分:1)