NetworkClient von Lutz
This commit is contained in:
parent
0664e1b73a
commit
73884f26c4
51
ws2012/P2P/uebungen/2/p2p_ex2/src/NetworkClient.java
Normal file
51
ws2012/P2P/uebungen/2/p2p_ex2/src/NetworkClient.java
Normal 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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user