Explain how to create and use sockets in java.
Client Side://creating client socket
socket=new Socket("localhost",4000); //InetAddress.getByName ("127.0.0.1")
//cretaing output stream for writting a data
write=new DataOutputStream(socket.getOutputStream());
//reading from a console
read=new DataInputStream(System.in);
String data=null;
while(true)
{
data=read.readLine();
write.writeUTF(data);
}
Server :
//creating severSocket object.
server=new ServerSocket(4000, 2);
System.out.println("Socket open");
//accept() method listens for a connection to be made to this socket and accepts it.
client=server.accept();
System.out.println("Client connected");
//receive inputs from client
receive=new DataInputStream(client.getInputStream());
String data=null;
while(true)
{
data=receive.readUTF();
System.out.println(data);
}
How to send to receive datagram packet?
DatagramSocket s = new DatagramSocket(null);s.bind(new InetSocketAddress(8888));
Which is equivalent to:
DatagramSocket s = new DatagramSocket(8888);
Both cases will create a DatagramSocket able to receive broadcasts on UDP port 8888.
One can create a packet as:
DatagramPacket packet = new DatagramPacket(message, message.length, address, DAYTIME_PORT);
To send or receive a packet, the sockets send or receive methods can be used:
socket.send(packet);
socket.receive(packet);
Comments
Post a Comment