NetworkClient von Lutz

This commit is contained in:
M.Scholz 2012-11-03 12:47:56 +01:00
parent 0664e1b73a
commit 73884f26c4

View File

@ -0,0 +1,51 @@
package u1;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Scanner;
public class NetworkClient {
private DatagramChannel channel;
private ByteBuffer buf;
private InetAddress inetaddr;
public NetworkClient(final String address, final int port) throws IOException {
inetaddr = InetAddress.getByName(address);
buf = ByteBuffer.allocate(1024);
channel = DatagramChannel.open();
channel.socket().connect(inetaddr, port);
buf.clear();
while (channel.socket().isConnected()) {
Scanner sc = new Scanner(System.in);
String instr = sc.nextLine();
channel.send(ByteBuffer.wrap(instr.getBytes()), new InetSocketAddress(inetaddr, port));
channel.configureBlocking(false);
channel.receive(buf);
String received = new String(buf.array());
System.out.println(received);
buf.clear();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
new NetworkClient("localhost", 1234);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}