Thursday, August 21, 2014

Starting Network Programming in Java

The InetAddress Class

InetAddress address = InetAddress.getByName(host);

InetAddress address = InetAddress.getLocalHost();

TCP Sockets

A communication link created via TCP/IP sockets is a connection-orientated link.

This means that the connection between server and client remains open throughout the duration of the dialogue between the two and is only broken (under normal circumstances) when one end of the dialogue formally terminates the exchanges.

Server
ServerSocket serverSocket = new ServerSocket(1234);
Socket link = serverSocket.accept();

Scanner input = new Scanner(link.getInputStream());
String input = input.nextLine();

//true will cause the output buffer to be fl ushed for every call of println
PrintWriter output = new PrintWriter(link.getOutputStream(),true);

link.close();

Client
Socket link = new Socket(InetAddress.getLocalHost(),1234);
Scanner input = new Scanner(link.getInputStream());

PrintWriter output = new PrintWriter(link.getOutputStream(),true);
Scanner userEntry = new Scanner(System.in);
String message = userEntry.nextLine();

Datagram (UDP) Sockets

Server

DatagramSocket datagramSocket = new DatagramSocket(1234);

byte[] buffer = new byte[256];
DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);

datagramSocket.receive(inPacket);

InetAddress clientAddress = inPacket.getAddress();
int clientPort = inPacket.getPort();

String message = new String(inPacket.getData(),0,inPacket.getLength());

DatagramPacket outPacket = new DatagramPacket(response.getBytes(), response.length(),clientAddress, clientPort);

datagramSocket.send(outPacket);

Client

DatagramSocket datagramSocket = new DatagramSocket();

DatagramPacket outPacket = new DatagramPacket(message.getBytes(), message.length(), host, PORT);

datagramSocket.send(outPacket);

byte[] buffer = new byte[256];

DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);

datagramSocket.receive(inPacket);

No comments:

Post a Comment