0

我正在尝试在服务器和客户端之间创建数据传输。连接已建立,但服务器和客户端之间没有数据传输。服务器端:

    public static void CreateServerSocket() {
    try {
        server = new ServerSocket(9999);
        t = new Thread(new SocketServer());
        t.start();
    } catch (IOException ex) {
        Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
    }

}

public static void closeServer() {
    try {
        server.close();
    } catch (IOException ex) {
        Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public static void sentSide(String side) {
    out.print(side);
}

@Override
public void run() {

    try {
        client = server.accept();
        out = new PrintWriter(client.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        out.print("test from server");
        while (true){
            strIn=in.readLine();
            System.out.println(strIn);
        }
    } catch (IOException ex) {
        Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

客户端:

public class SocketClient implements Runnable {

static Socket client;
static Thread t;
static PrintWriter out;
static BufferedReader in;
static String strIn;

public static boolean CreateClientSocket(InetAddress ip) {
    try {
        client = new Socket(ip, 9999);
        t = new Thread(new SocketClient());
        t.start();
        return true;
    } catch (UnknownHostException ex) {
        Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (IOException ex) {
        Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
}

public static void closeClient() {
    try {
        client.close();
    } catch (IOException ex) {
        Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

@Override
public void run() {
    try {
        out = new PrintWriter(client.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        out.print("test from client");
        while (true) {
            strIn = in.readLine();
            System.out.println(strIn);
            DialogMultiplayerStart.setSide(strIn);
        }
    } catch (IOException ex) {
        Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

问题是 out.print 没有发送数据。连接已建立,因为 CreateClientSocket 返回 true,但 out.print("test from client/server") 和 setSide 方法都不起作用。在此先感谢您的帮助。

4

1 回答 1

4

客户从做开始

out.print("test from client");

然后等待来自服务器的一整行:

strIn = in.readLine();

服务器开始做

out.print("test from server");

然后等待来自客户端的一整行:

strIn = in.readLine();

所以,双方都在等待对方发送行尾:死锁。

将其更改为

out.println("test from server");

out.println("test from client");

走得更远一点。但是你会遇到另一个问题:双方都在无限循环中读取,并且不再发送任何内容。

于 2013-07-28T13:56:25.883 回答