如何使客户端能够随时向服务器发送多条消息,从而使服务器始终监听消息 .
现在我写了一些代码,只允许我发送一次消息 . 我认为这是由于我关闭了输入/输出流和套接字 . 所以我现在已经玩了一段时间,我似乎无法做到!
客户:
public class Client {
private Socket socket;
private OutputStream os;
public Client() {}
public void connectToServer(String host, int port) {
try {
socket = new Socket(host, port);
} catch (IOException e) {
e.printStackTrace();
}
sendMessage();
}
public void sendMessage() {
try {
os = socket.getOutputStream();
String string = "Anthony";
byte[] b = string.getBytes(Charset.forName("UTF-8"));
os.write(b);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void STOP() {
stopOutput();
stopServer();
}
public void stopServer() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopOutput() {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器:
public class ConnectionHandler implements Runnable {
private Socket clientSocket;
private BufferedReader in;
public ConnectionHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
String clientAddress = clientSocket.getInetAddress().toString()
.substring(1);
System.out.println("Connected to " + clientAddress);
try {
in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
ArrayList data = new ArrayList();
String inputLine;
while ((inputLine = in.readLine()) != null) {
data.add(inputLine);
}
if (data.size() > 0) {
System.out.println(data.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void STOP() {
stopInput();
stopConnection();
}
public void stopInput() {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopConnection() {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在客户端的那一刻,我在套接字打开后立即发送消息,但是当我从另一个类调用send函数之后,它不会发送...
我该怎么做?或者我做错了什么?
提前致谢 .
附:我猜客户端服务器与服务器客户端是一样的,所以如果我知道如何做一种方式我可以轻松切换它...对吗?