Monday, 9 May 2016

Socket Programming

A simple program on Socket Handling.

Server File :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import java.io.*;  
import java.net.*;  
public class MyServer 
{  
 public static void main(String[] args)
 {  
  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);  
   ss.close();  
  }
  catch(Exception e)
  {
   System.out.println(e);
  }  
 }  
}  

Client File :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import java.io.*;  
import java.net.*;  
public class MyClient 
{  
 public static void main(String[] args) 
 {  
  try
  {      
   Socket s=new Socket("localhost",6666);  
   DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
   dout.writeUTF("Hello Server");  
   dout.flush();  
   dout.close();  
   s.close();  
  }
  catch(Exception e)
  {
   System.out.println(e);
  }  
 }  
}  

No comments:

Post a Comment

Thank you for spending your valuable time!