Java实现本地聊天A(TCP/IP)

public class ChatServer extends WebSocketServer {
// 自动绑定日期字段
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new DateEditorC());
}


// 无参构造/读取配置文件websocket.ip
public ChatServer() {
super(new InetSocketAddress(Integer.parseInt(ConfigUtils.getVal(
"config/chat.properties", "websocket.ip").split(":")[2])));
}


public ChatServer(int port) throws UnknownHostException {
super(new InetSocketAddress(port));
}


public ChatServer(InetSocketAddress address) {
super(address);
}


// 返回配置文件websocket.ip
public String getChatServerIp() {
return ConfigUtils.getVal("config/chat.properties", "websocket.ip")
.trim();
}


// 开启chat服务
@Override
public void start() {
try {
super.start();
} catch (Exception e) {
System.out.println("can only be started once");
}
}


// onOpen
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
}


// onClose
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
}


// onMessage
@Override
public void onMessage(WebSocket conn, String message) {
ChatMessage msgobj = JSON.parseObject(message, ChatMessage.class);
msgobj.setMsgtime(new Date());
setMsgFrom(conn, msgobj);
setMsgBody(msgobj);
this.sendToAll(JSON.toJSONString(msgobj));
}


// 设置msgfrom
private void setMsgFrom(WebSocket conn, ChatMessage msgobj) {
if (null == msgobj.getMsgfrom()
|| "".equals(msgobj.getMsgfrom().trim())) {
String cstr = conn.toString().trim();
msgobj.setMsgfrom("No." + cstr.split("@")[1]);
}
}


// 设置msgbody
private void setMsgBody(ChatMessage msgobj) {
String oldstr = msgobj.getMsgbody();
String newstr = HtmlUtils.getChatMsg(oldstr);
msgobj.setMsgbody(newstr);
}


// @Override
public void onFragment(WebSocket conn, Framedata fragment) {
System.out.println("received fragment: " + fragment);
}


@Override
public void onError(WebSocket conn, Exception ex) {
ex.printStackTrace();
if (conn != null) {
// some errors like port binding failed may not be assignable to a
// specific websocket
}
}


// 发送至公聊
public void sendToAll(String text) {
Collection<WebSocket> con = connections();
synchronized (con) {
for (WebSocket c : con) {
c.send(text);
}
}
}


}


class DateEditorC extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(text);
} catch (ParseException e) {
format = new SimpleDateFormat("yyyy-MM-dd");
try {
date = format.parse(text);
} catch (ParseException e1) {
e1.printStackTrace();
}
}
setValue(date);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值