java服务器和客户端_保持服务器和客户端之间的通信 - Java

如何使客户端能够随时向服务器发送多条消息,从而使服务器始终监听消息 .

现在我写了一些代码,只允许我发送一次消息 . 我认为这是由于我关闭了输入/输出流和套接字 . 所以我现在已经玩了一段时间,我似乎无法做到!

客户:

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函数之后,它不会发送...

我该怎么做?或者我做错了什么?

提前致谢 .

附:我猜客户端服务器与服务器客户端是一样的,所以如果我知道如何做一种方式我可以轻松切换它...对吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值