轻拔琴弦|java-websocket示例项目,可以直接使用

引入maven项目org.java-websocketJava-WebSocket1.5.1简单聊天室(群发聊天 , 上线提醒)服务端
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);}}


推荐阅读