package cz.woitee.websockets.examples;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;
import cz.woitee.websockets.ServerWebSocket;
import cz.woitee.websockets.WebSocket;
import cz.woitee.websockets.utils.UTF8String;
/**
* Example usage of Java SE WebSocket Server.
* Compiled example with javascript client can be found <a href=www.woitee.cz/java-websockets/>here</a>.
*
* Showing the ServerWebSocket used quite the same as you would use a java.net.ServerSocket.
*
* @author woitee
*/
public class ExampleServer {
JLabel incoming = new JLabel();
JTextField outgoing = new JTextField();
JButton btnSend = new JButton("Send");
public ExampleServer() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
startServer();
}
private void onException(Exception e) {
e.printStackTrace();
}
private void createAndShowGUI() {
JFrame frame = new JFrame("WebSockets");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cont = frame.getContentPane();
cont.setLayout(new GridLayout(0, 1));
cont.add(incoming);
Box box = new Box(BoxLayout.X_AXIS);
cont.add(box);
box.add(outgoing);
outgoing.setEnabled(false);
box.add(btnSend);
//erase text on focus
outgoing.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent arg0) {
}
@Override
public void focusGained(FocusEvent arg0) {
outgoing.setText("");
}
});
frame.pack();
frame.setVisible(true);
}
private void startServer() {
ServerWebSocket swSocket = null;
WebSocket socket = null;
try {
InetAddress addr = InetAddress.getByName(null);
int port = 11854;
swSocket = new ServerWebSocket(port, 10, addr);
incoming.setText("Starting to listen on port: "+port);
try {
socket = swSocket.accept();
try {
handleConnection(socket);
} finally {
socket.close();
}
} catch (IOException e) {
onException(e);
} finally {
swSocket.close();
}
} catch (IOException e) {
onException(e);
}
}
private void handleConnection(WebSocket socket) throws IOException {
incoming.setText("Connection established.");
outgoing.setEnabled(true);
final OutputStream output = socket.getOutputStream();
final InputStream input = socket.getInputStream();
//handle outgoing messages
btnSend.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
output.write(new UTF8String(outgoing.getText()).array());
} catch (IOException e) {
onException(e);
}
}
});
//handle incoming messages
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
try {
while ((line = reader.readLine()) != null) {
incoming.setText(line);
}
} catch (IOException e) {
onException(e);
}
}
public static void main(String[] args) {
new ExampleServer();
}
}