【问题标题】:Java: socket not getting inputJava:套接字没有得到输入
【发布时间】:2015-07-13 04:29:47
【问题描述】:

所以,我正在做一个井字游戏项目,我的网络部分有问题,已经全部完成,只是缺少连接玩家彼此的部分,这是有问题的课程:

public class Enemy implements Runnable{
    private static Socket enemy;

    public Enemy(Socket sock){
        enemy = sock;
    }

    public static void passaJogada(int xPos, int yPos){
        try {
            PrintWriter saida = new PrintWriter(enemy.getOutputStream());
            String x = "" + xPos;
            saida.println(x);
            String y = "" + yPos;
            System.out.print(x + y);
            saida.println(y);

        } catch (IOException e) {
            System.out.println("Ocorreu um erro!");
        }    
    }

    public void run() {
        try {
            BufferedReader entrada = new BufferedReader(new InputStreamReader(enemy.getInputStream()));
            while(!EndGameWindow.getEnd()) {    
                int x = Integer.parseInt(entrada.readLine());
                int y = Integer.parseInt(entrada.readLine());
                GameWindow.gameButton[x][y].fazerJogada(x,y);
            }
            entrada.close();
        } catch (IOException e) {
            System.out.println("Um errro ocorreu!");
        }
    }
}

我不知道发生了什么,我只知道 PrintWriter 正在写入但 BufferedReader 没有读取。

只需忽略变量和方法的葡萄牙语名称。

【问题讨论】:

  • Socket 的另一端是否为readLine() 编写了正确的分隔符(例如换行符)?
  • 套接字的另一端是 passaJogada 方法,它使用 println 方法打印一个只有 int 的字符串。

标签: java sockets input io output


【解决方案1】:

请参阅PrintWriter 的 API,尤其是您正在使用的单参数 OutputStream 构造函数:

从现有的 OutputStream 创建一个新的 PrintWriter,没有自动行刷新。

换句话说,PrintWriter 是缓冲的,需要刷新。要启用自动行刷新,请使用适当的构造函数

PrintWriter saida = new PrintWriter(enemy.getOutputStream(), true);

...或显式刷新 PrintWriter:

....
saida.println(y);
saida.flush();

【讨论】:

  • 哇,成功了!!谢谢老兄,对不起,我不能为你的帖子投票。
【解决方案2】:

我假设您希望玩家互相玩,即使他们都没有坐在服务器“游戏”所在的计算机上。在这种情况下,您应该做的是将游戏与网络分开。我还将假设您已将所有游戏部分都按其应有的方式工作。所以这就是你可以做的。 1)首先创建一个只连接到服务器部分的类,您可以将其命名为服务器(参见下面的示例代码)。 2)创建另一个类来制作这些客户端的对象(在你的情况下是玩家)。(再次查看下面的代码) 3) 然后你可以让他们与游戏互动。

如果您在修复它时遇到问题,请告诉我,也许我可以为您提供更多详细信息。

你这个简单的服务器部分。

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by baljit on 03.05.2015.
 * @author Baljit Sarai
 */

public class Server {
    ServerSocket serverSocket;
    public static List<ClientConnection> clientConnectionList = new ArrayList<ClientConnection>();
    public Server() {
        try {
            serverSocket = new ServerSocket(12345);
            System.out.println("Server started");
        } catch (IOException ioe) {
            System.out.println("Something went wrong");
        }
    }




public void serve(){
    Socket clientSocket;
    try {
        while((clientSocket = serverSocket.accept()) != null){
            System.out.println("got client from"+clientSocket.getInetAddress());
            ClientConnection clientConnection = new ClientConnection(clientSocket);
            clientConnectionList.add(clientConnection);
            ClientHandler clientHandler = new ClientHandler(clientConnection,serverSocket);
            clientHandler.start();
        }
    }catch (IOException ioe){
        System.out.println("Something went wrong");
     }
    }
}

在这种情况下,clientConnection 可以是您应该制作的播放器对象,只是为了让您自己更轻松。

clientHandler是可以同时处理每个玩家的类。

这里的“clientConnectionList”只是用来存储连接,以便您知道在哪里可以找到它们。

所以这里是 ClientConnection 类。

import java.io.*;
import java.net.Socket;

/**
 * Created by baljit on 03.05.2015.
 * @author Baljit Sarai
 */
public class ClientConnection {
    private Socket connection;
    private DataInputStream streamIn;
    private DataOutputStream streamOut;
    private BufferedInputStream bufferedInputStream;
    public ClientConnection(Socket socket){
        connection = socket;
        try{

            bufferedInputStream = new BufferedInputStream(connection.getInputStream());
            streamIn = new DataInputStream(bufferedInputStream);
            streamOut = new DataOutputStream(connection.getOutputStream());
        }catch (IOException ioe){
            System.out.println("Something went wrong when trying create the Connection Object");
        }
    }

    public boolean isBound(){
        return connection.isBound();
    }    
    public DataInputStream getStreamIn() {
        return streamIn;
    }

    public DataOutputStream getStreamOut() {
        return streamOut;
    }

    public void close(){
        try{

            connection.close();
        }catch (IOException ioe){
            System.out.print("Something went wrong trying to close the connection");
        }
    }

    public String getAddress(){
        return connection.getInetAddress().toString();
    }




}

这里是 ClientHandler 类

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by baljit on 03.05.2015.
 * @author Baljit Sarai
 */
public class ClientHandler extends Thread{
    private ServerSocket serverSocket;
    String data;
    ClientConnection connection;

    public ClientHandler(ClientConnection clientConnection, ServerSocket serverSocket) {
        connection = clientConnection;
    }

    public void makeMove(String data){
        //This is where you put the logic for how the server can 
        //interpetate the readed data to a game move

    }

    @Override
    public void run(){
        System.out.println("ClientHandler running");
        try{
            while(connection.isBound()){
                data= connection.getStreamIn().readUTF();
                this.makeMove(data);
            }
            connection.close();
        }catch (IOException ioe){
            System.out.println("Connection dead "+connection.getAddress());
            Server.clientConnectionList.remove(connection);
        }
    }
}

请让我知道它对您的效果如何。也许我可以更好地帮助你:)祝你好运:)

【讨论】:

  • 我已经有一个专门用于网络的类,它有一些用于 UI 的 javafx,如果你愿意,我可以发布所有代码来帮助我(如果可以的话)。
  • 我也是新手。我还是学生。但我喜欢帮助并尝试解决这些问题。将代码链接给我,以便至少可以看到,也许我可以改进并帮助您处理代码。
  • 1.你还没有展示如何发送。 2.Socket.isBound()在连接后永远不会返回false。它不是连接有效性的有效测试。没有:但是readUTF() 在流结束时抛出EOFException,而您没有抓住它并正确处理它。
  • 我只是想展示将人们连接到套接字的 bacis 方式。我知道代码需要更正。我只是想帮助他。如果你愿意,我可以润色代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多