我正在尝试在服务器和客户端之间创建数据传输。连接已建立,但服务器和客户端之间没有数据传输。服务器端:
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 方法都不起作用。在此先感谢您的帮助。