Socket Programming With UDP and TCP
Socket Programming With UDP and TCP
Socket Programming With UDP and TCP
and TCP
Socket Programming with TCP
• Connection oriented
– Handshaking procedure
• Reliable byte-stream
TCP-client in Java
import java.io*;
import java.net.*;
Class TCPClient {
public static void main (String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(system.in));
Socket clientSocket = new Socket(”hostname”, 6789);
DataOutpuStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + ’\n’);
modifiedSentence = inFromServer.readLine();
System.out.println(”FROM SERVER: ” + modifiedSentence);
clientSocket.close(); } }
TCP-client in Java
import java.io*;
import java.net.*;
• Connectionless
• No reliable datatransfer
UDP-client in Java
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String args[ ]) throws Exception {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(”hostname”);
byte[ ] sendData = new byte[1024];
byte[ ] recieveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes ();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modefiedSentence = new String(receivePacket.getData());
System.out.println(”FROM SERVER:” + modifiedSentence);
clientSocket.close();
} }
UDP-client in Java
DatagramSocket clientSocket = new DatagramSocket();