Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- UDP
- ------------------Client-------------------------
- import java.io.*;
- import java.net.*;
- public class client{
- public static void main(String[] args) throws IOException{
- DatagramSocket client = new DatagramSocket();
- InetAddress add = InetAddress.getByName("localhost");
- String msg = "Hello Server";
- byte[] buf = msg.getBytes();
- DatagramPacket packet = new DatagramPacket(buf, buf.length,add,1234);
- client.send(packet);
- client.close();
- }
- }
- ---------------------Server-------------------------
- import java.io.*;
- import java.net.*;
- public class server {
- public static void main(String[] args) throws IOException{
- DatagramSocket server = new DatagramSocket(1234);
- byte[] buf = new byte[256];
- DatagramPacket packet = new DatagramPacket(buf,buf.length);
- server.receive(packet);
- String response = new String(packet.getData());
- System.out.println("Response Data :: "+response);
- server.close();
- }
- }
- ---------------------------------------------------------------------------
- TCP
- ------------------Client-------------------------
- import java.io.*;
- import java.net.*;
- import java.util.Scanner;
- public class client{
- public static void main(String[] args) {
- try{
- Scanner sc = new Scanner(System.in);
- Socket s=new Socket("localhost",6666);
- DataOutputStream dout=new DataOutputStream(s.getOutputStream());
- System.out.println("Establishing Connection...");
- System.out.println("Connection Established");
- System.out.println("Enter the message to be sent:");
- String str = sc.nextLine();
- dout.writeUTF(str);
- dout.flush();
- dout.close();
- System.out.println("Connection Closed");
- s.close();
- sc.close();
- }catch(Exception e){System.out.println(e);}
- }
- }
- -----------------------------Server-------------------
- import java.io.*;
- import java.net.*;
- public class server {
- public static void main(String[] args) throws Exception {
- try{
- ServerSocket ss=new ServerSocket(6666);
- Socket s=ss.accept();//establishes connection
- DataInputStream dis=new DataInputStream(s.getInputStream());
- String str=(String)dis.readUTF();
- System.out.println("message: "+str);
- System.out.println("Connection Closed");
- ss.close();
- }catch(Exception e){System.out.println(e);}
- }
- }
Add Comment
Please, Sign In to add comment