概述
public class ClientHeart extends Thread {
@Override
public void run() {
try {
while (true) {
ClientSender.getInstance().send();
synchronized (ClientHeart.class) {
// this.wait(5000);
Thread.sleep(2000);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 程序的入口main方法
*
* @param args
*/
public static void main(String[] args) {
ClientHeart client = new ClientHeart();
client.start();
}
}
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class ClientSender {
private ClientSender() {
}
Socket sender = null;
private static ClientSender instance;
public static ClientSender getInstance() {
if (instance == null) {
synchronized (ClientHeart.class) {
instance = new ClientSender();
}
}
return instance;
}
public void send() {
try {
sender = new Socket(InetAddress.getLocalHost(), 9090);
while (true) {
ObjectOutputStream out = new ObjectOutputStream(sender.getOutputStream());
Entity obj = new Entity();
obj.setName("xiaoming");
obj.setSex("男");
out.writeObject(obj);
out.flush();
System.out.println("已发送...");
Thread.sleep(5000);
}
} catch (Exception e) {
}
}
}
import java.io.Serializable;
public class Entity implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Entity [name=" + name + ", sex=" + sex + "]";
}
}
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerHeart extends Thread {
private ServerSocket server = null;
Object obj = new Object();
@Override
public void run() {
try {
server = new ServerSocket(9090);
while (true) {
Socket client = server.accept();
synchronized (obj) {
new Thread(new Client(client)).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 客户端线程
*
* @author USER
*
*/
class Client implements Runnable {
Socket client;
public Client(Socket client) {
this.client = client;
}
@Override
public void run() {
try {
while (true) {
ObjectInput in = new ObjectInputStream(client.getInputStream());
Entity entity = (Entity) in.readObject();
System.out.println(entity);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 程序的入口main方法
*
* @param args
*/
public static void main(String[] args) {
System.out.println("开始检测客户端是否在线...");
new ServerHeart().start();
}
}
最后
以上就是生动萝莉为你收集整理的Socket 客户端 服务端 心跳监测的全部内容,希望文章能够帮你解决Socket 客户端 服务端 心跳监测所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复