Skip to content

Instantly share code, notes, and snippets.

@alterakey
Created November 14, 2012 12:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alterakey/4071810 to your computer and use it in GitHub Desktop.
Save alterakey/4071810 to your computer and use it in GitHub Desktop.
Android NIO experiment
package com.gmail.altakey.nio;
import android.app.Activity;
import android.os.Bundle;
import android.os.AsyncTask;
import java.nio.*;
import java.nio.channels.SocketChannel;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Arrays;
public class ClientActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new ClientTask().execute();
}
public class ClientTask extends AsyncTask<Void, Void, Void> {
@Override
public Void doInBackground(Void... args) {
try {
connect();
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void connect() throws Exception {
InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName("10.0.0.60"), 8000);
SocketChannel sc = null;
try {
// Connect
sc = SocketChannel.open();
sc.connect(isa);
// Read the time from the remote host. For simplicity we assume
// that the time comes back to us in a single packet, so that we
// only need to read once.
byte[] message = UdpUtil.messageToByteMessage(new messages.Teste("hello there"));
ByteBuffer buf = ByteBuffer.wrap(message);
sc.write(buf);
}
finally {
// Make sure we close the channel (and hence the socket)
if (sc != null) {
sc.close();
}
}
}
}
public static class UdpUtil {
public static byte[] messageToByteMessage(messages.Teste msg) {
byte[] data = Arrays.copyOfRange(msg.buffer, 0, 128);
return data;
}
}
private static class messages {
public static class Teste {
public byte[] buffer;
public Teste(String message) {
buffer = message.getBytes();
}
}
}
}
$ python ./server.py
Connected by ('10.0.0.60', 54268)
Connected by ('10.0.0.60', 54268) closed
Connected by ('10.0.0.60', 54271)
Connected by ('10.0.0.60', 54271) closed
Connected by ('10.0.0.60', 54273)
Connected by ('10.0.0.60', 54273) closed
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", 8000))
s.listen(100)
while 1:
conn, addr = s.accept()
print 'Connected by %s' % repr(addr)
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
print 'Connected by %s closed' % repr(addr)
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment