Skip to content

Instantly share code, notes, and snippets.

@codenameone
Created January 8, 2014 08:36
Show Gist options
  • Save codenameone/8313627 to your computer and use it in GitHub Desktop.
Save codenameone/8313627 to your computer and use it in GitHub Desktop.
Socket demo application
public class MyApplication {
private Form current;
public void init(Object context) {
try {
Resources theme = Resources.openLayered("/theme");
UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
} catch(IOException e){
e.printStackTrace();
}
}
public void start() {
if(current != null){
current.show();
return;
}
final Form soc = new Form("Socket Test");
Button btn = new Button("Create Server");
Button connect = new Button("Connect");
final TextField host = new TextField("127.0.0.1");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
soc.addComponent(new Label("Listening: " + Socket.getIP()));
soc.revalidate();
Socket.listen(5557, SocketListenerCallback.class);
}
});
connect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Socket.connect(host.getText(), 5557, new SocketConnection() {
@Override
public void connectionError(int errorCode, String message) {
System.out.println("Error");
}
@Override
public void connectionEstablished(InputStream is, OutputStream os) {
try {
int counter = 1;
while(isConnected()) {
os.write(("Hi: " + counter).getBytes());
counter++;
Thread.sleep(2000);
}
} catch(Exception err) {
err.printStackTrace();
}
}
});
}
});
soc.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
soc.addComponent(btn);
soc.addComponent(connect);
soc.addComponent(host);
soc.show();
}
public static class SocketListenerCallback extends SocketConnection {
private Label connectionLabel;
@Override
public void connectionError(int errorCode, String message) {
System.out.println("Error");
}
private void updateLabel(final String t) {
Display.getInstance().callSerially(new Runnable() {
public void run() {
if(connectionLabel == null) {
connectionLabel = new Label(t);
Display.getInstance().getCurrent().addComponent(connectionLabel);
} else {
connectionLabel.setText(t);
}
Display.getInstance().getCurrent().revalidate();
}
});
}
@Override
public void connectionEstablished(InputStream is, OutputStream os) {
try {
byte[] buffer = new byte[8192];
while(isConnected()) {
int pending = is.available();
if(pending > 0) {
int size = is.read(buffer, 0, 8192);
if(size == -1) {
return;
}
if(size > 0) {
updateLabel(new String(buffer, 0, size));
}
} else {
Thread.sleep(50);
}
}
} catch(Exception err) {
err.printStackTrace();
}
}
}
public void stop() {
current = Display.getInstance().getCurrent();
}
public void destroy() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment