【发布时间】:2015-02-16 00:46:39
【问题描述】:
如何让客户端能够随时向服务器发送多条消息,从而使服务器始终监听消息。
现在我写了一些代码,只允许我发送一次消息。我认为这是因为我关闭了输入/输出流和套接字。所以我已经玩了一段时间了,我似乎做不到!
客户:
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<String> data = new ArrayList<String>();
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 函数后它不会发送...
我应该怎么做?还是我做错了什么?
提前致谢。
附言我猜客户端-服务器与服务器-客户端是一样的,所以如果我知道如何做一种方法,我可以轻松地切换它......对吗?
【问题讨论】:
-
了解名为多线程的概念
标签: java sockets client server serversocket