我正在尝试在服务器和客户端之间创建数据传输。建立连接,但服务器和客户端之间没有数据传输。 服务器端:
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(“来自客户端/服务器的测试”)都没有工作,也没有setSide方法。在此先感谢您的帮助。
答案 0 :(得分: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");
走得更远。但是你会遇到另一个问题:双方都在无限循环中阅读,而且不再发送任何东西。