轻拔琴弦|java-websocket示例项目,可以直接使用
引入maven项目
简单聊天室(群发聊天 , 上线提醒)服务端
package com.test.test1;import org.java_websocket.WebSocket;import org.java_websocket.handshake.ClientHandshake;import org.java_websocket.server.WebSocketServer;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.InetSocketAddress;public class tServer extends WebSocketServer {//封装端口public tServer(int port){super(new InetSocketAddress(port));}public static void main(String[] args) throws IOException {int port = 1234;//当用户指定端口时使用//port = Integer.parseInt(args[0]);tServer t = new tServer(port);t.start();System.out.println("服务端启动 。端口为"+t.getPort());//获取控制台输入BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));while (true){String in = sysin.readLine();t.broadcast(in);}}@Overridepublic void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {System.out.println("客户端连接");//向连接的机器发送消息webSocket.send("欢迎加入服务中心");//向所有的机器发送消息broadcast("新的设备加入:"+clientHandshake.getResourceDescriptor());System.out.println(webSocket.getRemoteSocketAddress().getAddress().getHostAddress()+"进入服务组");}@Overridepublic void onClose(WebSocket webSocket, int i, String s, boolean b) {System.out.println("客户端断开连接");System.out.println(webSocket+"====>"+i+"===>"+s+"====>"+b);}@Overridepublic void onMessage(WebSocket webSocket, String s) {System.out.println("服务端收到消息");System.out.println(webSocket+"===>"+s);}@Overridepublic void onError(WebSocket webSocket, Exception e) {System.out.println("服务端出现错误");}@Overridepublic void onStart() {System.out.println("服务端启动成功");//设备超时时间setConnectionLostTimeout(0);setConnectionLostTimeout(100);}}
客户端(使用的JFrame)
package com.test.test1;public class ChatClient extends JFrame implements ActionListener {private static final long serialVersionUID = -6056260699202978657L;private final JTextField uriField;private final JButton connect;private final JButton close;private final JTextArea ta;private final JTextField chatField;private final JComboBox draft;private WebSocketClient cc;public ChatClient(String defaultlocation) {super("WebSocket Chat Client");Container c = getContentPane();GridLayout layout = new GridLayout();layout.setColumns(1);layout.setRows(6);c.setLayout(layout);Draft[] drafts = {new Draft_6455()};draft = new JComboBox(drafts);c.add(draft);uriField = new JTextField();uriField.setText(defaultlocation);c.add(uriField);connect = new JButton("Connect");connect.addActionListener(this);c.add(connect);close = new JButton("Close");close.addActionListener(this);close.setEnabled(false);c.add(close);JScrollPane scroll = new JScrollPane();ta = new JTextArea();scroll.setViewportView(ta);c.add(scroll);chatField = new JTextField();chatField.setText("");chatField.addActionListener(this);c.add(chatField);java.awt.Dimension d = new java.awt.Dimension(300, 400);setPreferredSize(d);setSize(d);addWindowListener(new java.awt.event.WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {if (cc != null) {cc.close();}dispose();}});setLocationRelativeTo(null);setVisible(true);}@Overridepublic void actionPerformed(ActionEvent e) {if (e.getSource() == chatField) {if (cc != null) {cc.send(chatField.getText());chatField.setText("");chatField.requestFocus();}} else if (e.getSource() == connect) {try {// cc = new ChatClient(new URI(uriField.getText()), area, ( Draft ) draft.getSelectedItem() );cc = new WebSocketClient(new URI(uriField.getText()), (Draft) draft.getSelectedItem()) {@Overridepublic void onMessage(String message) {ta.append("got: " + message + "\n");ta.setCaretPosition(ta.getDocument().getLength());}@Overridepublic void onOpen(ServerHandshake handshake) {ta.append("You are connected to ChatServer: " + getURI() + "\n");ta.setCaretPosition(ta.getDocument().getLength());}@Overridepublic void onClose(int code, String reason, boolean remote) {ta.append("You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason+ "\n");ta.setCaretPosition(ta.getDocument().getLength());connect.setEnabled(true);uriField.setEditable(true);draft.setEditable(true);close.setEnabled(false);}@Overridepublic void onError(Exception ex) {ta.append("Exception occurred ...\n" + ex + "\n");ta.setCaretPosition(ta.getDocument().getLength());ex.printStackTrace();connect.setEnabled(true);uriField.setEditable(true);draft.setEditable(true);close.setEnabled(false);}};close.setEnabled(true);connect.setEnabled(false);uriField.setEditable(false);draft.setEditable(false);cc.connect();} catch (URISyntaxException ex) {ta.append(uriField.getText() + " is not a valid WebSocket URI\n");}} else if (e.getSource() == close) {cc.close();}}public static void main(String[] args) {String location;if (args.length != 0) {location = args[0];System.out.println("Default server url specified: \'" + location + "\'");} else {location = "ws://localhost:1234";System.out.println("Default server url not specified: defaulting to \'" + location + "\'");}new ChatClient(location);}}
推荐阅读
- 轻拔琴弦|体现着一个人的修养涵养,使用手机
- 轻拔琴弦最惨的不是华为,中兴被美国罚款23亿美元,如今逆袭崛起!
- 上海市徐汇区人民政府门户网站|拨动竖琴的琴弦,画下夕阳下的“馄饨皮”,上海交响乐团的文化集市如此有趣
- 后海大鲨鱼|《乐夏2》被黑最惨的乐队,重回舞台后躁到扔话筒、拆琴弦!
- 轻拔琴弦从差点倒闭到年入10亿,创米李建新:没到最后,我绝不投降
- 轻拔琴弦|构陷华为的汇丰卷入洗钱案件,这回还能洗白?,再次陷入大丑闻
- 轻拔琴弦|Games宣布《堡垒之夜:拯救世界》将不再能在macOS上玩了,Epic
- 轻拔琴弦Epic Games宣布《堡垒之夜:拯救世界》将不再能在macOS上玩了
- 轻拔琴弦 却成为了引领者,“疯子”诺基亚当年发布像素4100万的神机
- 轻拔琴弦我才发现,微信里面有一个功能,能将手机照片自动拼成长图