在服务器上,当我获得新连接(serverSocket.accept()
)时,
我将该连接套接字传递给名为ServerPlayer.java的类的实例,
它从一个主题扩展而来。
我还创建了一个OutputObjectStream和一个InputObjectStream,并将它们传递给新的ServerPlayer实例,然后将ServerPlayer实例添加到ArrayList中以跟踪它们。
当我在新的ServerPlayer上调用start()
时,我让它写了一个字节(1)。
然后让我的客户端运行一个侦听线程,该线程侦听来自TCP服务器的传入数据。但是,我没有收到我从服务器发送的(1)。我不确定服务器是否正常发送或客户端是否未正确接收...
ServerPlayer.java:
/**
* ServerPlayer.java
* Creates a new instance of a player on the server, gives it
* an output and input stream, as well as the socket it came in on
*/
package server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ServerPlayer extends Thread {
UIServer ui;
Socket socket;
ObjectOutputStream os;
ObjectInputStream is;
int id = -1;
ServerPlayer(Socket socket, ObjectOutputStream os, ObjectInputStream is, UIServer ui){
this.socket = socket;
this.os = os;
this.is = is;
this.ui = ui;
}
public void setID(int id){
this.id = id;
}
public int getID(){
return this.id;
}
public void run(){
boolean keepGoing = true;
System.out.println("SERVERPLAYER THREAD START");
try {
os.writeByte(1);
System.out.println("sent byte 1 from server");
} catch (IOException ex) {
Logger.getLogger(ServerPlayer.class.getName()).log(Level.SEVERE, null, ex);
}
while(keepGoing){
try{
Byte msg = is.readByte();
int mes_id = msg.intValue();
ui.console.println("SERV MESSAGE#: " + mes_id);
} catch (IOException ex) {
Logger.getLogger(ServerPlayer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
ListenFromServer.Java:
/*
* ListenFromServer.java
* Listens for incoming data from the TCP Server (this is on the client side)
*/
package client;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ListenFromServer extends Thread {
TCPClient client;
boolean isRunning = false;
public ListenFromServer(TCPClient client){
this.client = client;
}
public void run(){
System.out.println("listen from server thread start");
isRunning = true;
while(isRunning){
try {
Byte b = client.sInput.readByte();
client.ui.console.println("BYTE: " + b.intValue());
} catch (IOException ex) {
Logger.getLogger(ListenFromServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
答案 0 :(得分:0)
尝试更改为
os.writeByte(1);
os.flush();