java tcp协议传输,客户端怎么判断,服务端有没有来消息...,通过循环...
发布网友
发布时间:2024-09-07 06:50
我来回答
共1个回答
热心网友
时间:2024-09-29 11:55
给你一个简单的例子,这样就是客户端不停的接收消息,你说的对,是通过循环在一直的读取。
---------------------------------------------------------------------------
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ScoketTest {
public static void main(String[] args) throws Exception {
new Server().start();
new Client().start();
}
}
class Server extends Thread {
private ServerSocket server = null;
public Server() throws Exception {
server = new ServerSocket(8888);
}
public void run() {
try {
while (true) {
Socket client = server.accept();
OutputStream out = client.getOutputStream();
out.write("server to client : hello".getBytes());
out.flush();
out.close();
client.close();
sleep(1000);
}
} catch (Exception e) {
System.out.println("server : " + e.getMessage());
}
}
}
class Client extends Thread {
public void run() {
try {
while (true) {
Socket client = new Socket("localhost", 8888);
InputStream in = client.getInputStream();
byte[] buff = new byte[4096];
StringBuffer sbuff = new StringBuffer();
int len = 0;
while ((len = in.read(buff)) != -1) {
sbuff.append(new String(buff, 0, len));
}
in.close();
client.close();
System.out.println(sbuff.toString());
sleep(1000);
}
} catch (Exception e) {
System.out.println("client : " + e.getMessage());
}
}
}