本文介绍了Java套接字-客户端不会从服务器的套接字读取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个Java项目,它们通过字符串与套接字进行通信.一个是客户端,另一个是服务器.服务器通过"ServerSocket"接受连接,并使用新创建的"Socket"创建新的"Session"(线程).

I have two Java projects that communicate with sockets through strings. One is a client and the other is a server. The server accepts the connection trough the "ServerSocket" and creates a new "Session" (Thread) with a freshly created "Socket".

与此同时,客户端只有一个套接字",一旦连接了该套接字,客户端就会创建一个"ClientSession"(线程,与会话"非常相似).

Meanwhile, the client only has a "Socket", once that socket is connected, the client creates a "ClientSession" (Thread, pretty similar to "Session).

我想要的是服务器通过"USERNAME"字符串向客户端询问其用户名,然后由客户端使用其用户名进行回答.但是答案永远不会回来.我认为这可能是BufferedReader和PrintWriter行在错误的位置触发的同步问题.

What I want is the server to ask the client his username through the "USERNAME" string, and the client to answers with his username. But the answer never come back. I think it's maybe a synchronisation problem with the BufferedReader and the PrintWriter lines fired at the wrong place.

-----------服务器代码-----------------

-----------Server Code---------------

登录类别:

public class Login implements Runnable {

private ArrayList<Session> sessions;
private int port;
private Thread thread;
private ServerSocket serverSocket;
private Game game;

public Login(int port, Game game) throws Exception {
    this.sessions = new ArrayList();
    this.port = port;
    this.serverSocket = new ServerSocket(port);
    this.game = game;
    this.thread = new Thread(this);
    this.thread.start();
}

@Override
public void run() {
    while(true) {
        Socket socket;
        try {
            System.out.println("[Server Network] Waiting for a new player to log in.");
            socket = serverSocket.accept();
            sessions.add(new Session(socket,this));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

public void addPlayer(Player p) {
    this.game.addPlayer(p);
}

}

会话类:

public class Session implements Runnable {

private String username;
private Thread thread;
private Socket socket;
private BufferedReader br;
private OutputStreamWriter os;
private PrintWriter out;
private Login login;

private boolean ready;

public Session(Socket socket, Login login) throws IOException {
    this.login = login;
    this.socket = socket;
    this.ready = false;

    this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    this.os = new OutputStreamWriter(socket.getOutputStream());
    this.out = new PrintWriter(os);

    System.out.println("[Server network] Session created for client with ip: "+socket.getInetAddress().getHostAddress());

    this.thread = new Thread(this);
    this.thread.start();
}

public void send(String m) {
    System.out.println("[Server network] Sending message: "+m);
    out.write(m);
    out.flush();
    System.out.println("[Server network] Message sent: "+m);
}


@Override
public void run() {
    while (true) {
        if (!ready) {
            try {
                this.send("USERNAME");
                this.username = br.readLine();
                this.ready = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            String request = br.readLine();
            System.out.println(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

}

-----------客户代码-------------

-----------Client Code-------------

游戏类:

public class Game {

private Window window;

private LocalPlayer localPlayer;
private ArrayList<Player> players;
private Map map;

private String username;

private String serverIpAddress;
private ClientSession clientSession;
private static int port = 23123;

public Game(Window window, Map map) throws UnknownHostException, IOException {
    System.out.println("Game Launched.");

    //Asks for the server ip address and creates a session.
    //this.serverIpAddress = JOptionPane.showInputDialog(null,"Please enter the server ip address.",JOptionPane.QUESTION_MESSAGE);
    this.serverIpAddress = "localhost";

    //this.username = JOptionPane.showInputDialog(null,"What is your username?",JOptionPane.QUESTION_MESSAGE);
    this.username = "GriffinBabe";

    this.clientSession = new ClientSession(new Socket(serverIpAddress,port),this);

    this.window = window;
    this.localPlayer = new LocalPlayer(new Warrior(),this.username,'R');
    this.map = map;

}

public LocalPlayer getLocalPlayer() {
    return this.localPlayer;
}

public Map getMap() {
    return map;
}

}

ClientSession类:

ClientSession Class:

public class ClientSession implements Runnable {

private Socket socket;
private Thread thread;
private BufferedReader br;
private OutputStreamWriter os;
private PrintWriter out;
private Game game;

public ClientSession(Socket socket, Game game) throws IOException {
    this.game = game;
    this.socket = socket;

    this.br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
    this.os = new OutputStreamWriter(this.socket.getOutputStream());
    this.out = new PrintWriter(os);

    System.out.println("[Client network] Session created for server with ip: "+socket.getInetAddress().getHostAddress());

    this.thread = new Thread(this);
    this.thread.start();
}

public void send(String m) {
    System.out.println("[Client network] Sending message: "+m);
    out.write(m);
    out.flush();
    System.out.println("[Client network] Message sent: "+m);
}

@Override
public void run() {
    while(true) {
        try {
            String request = br.readLine();
            System.out.println(request);
            switch (request) {
            case "USERNAME":
                send(game.getLocalPlayer().getUsername());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

}

这是控制台日志:

服务器(首先启动):

客户:

推荐答案

您的服务器发送"USERNAME",然后等待.客户端读取下一行,并阻塞直到接收到它.由于服务器从不发送EOL字符,因此您将陷入僵局.如果客户端读取一行,则服务器应发送一行.

Your server sends "USERNAME" and then waits. The client reads the next line, and blocks until it receives it. So you have a deadlock, since the server never sends an EOL character. If the client reads a line, the server should send a line.

这篇关于Java套接字-客户端不会从服务器的套接字读取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:02