example of java socket programming
example
//clint program
import java.net.*;
import java.io.*;
import java.util.*;
public class myclint
{
public static void main(String args[])throws IOException
{
Socket cs= new Socket("localhost",1254);//open connection
Scanner ins=new Scanner(cs.getInputStream());
PrintWriter outs=new PrintWriter(cs.getOutputStream(),true);//perform IO
outs.println("hello Server");
String s=ins.nextLine();
System.out.println("from server::"+s);//close stream and connection
ins.close();
outs.close();
cs.close();
}
}
//server program
import java.net.*;
import java.io.*;
import java.util.*;
public class myserver
{
public static void main(String args[])throws IOException
//Register server on port 1234
{
ServerSocket ss= new ServerSocket(1234);//wait and accept a connection
Socket cs=ss.accept();//get a communication stream associated with the socket
Scanner ins =new Scanner(cs.getInputStream());
PrintWriter outs= new PrintWriter(cs.getOutputStream(),true);//perform
String s=ins.nextLine();
System.out.println("hello client:"+s);
outs.println("hello clint");//close stream and connection
outs.close();
ins.close();
cs.close();
ss.close();
}
}
//clint program
import java.net.*;
import java.io.*;
import java.util.*;
public class myclint
{
public static void main(String args[])throws IOException
{
Socket cs= new Socket("localhost",1254);//open connection
Scanner ins=new Scanner(cs.getInputStream());
PrintWriter outs=new PrintWriter(cs.getOutputStream(),true);//perform IO
outs.println("hello Server");
String s=ins.nextLine();
System.out.println("from server::"+s);//close stream and connection
ins.close();
outs.close();
cs.close();
}
}
//server program
import java.net.*;
import java.io.*;
import java.util.*;
public class myserver
{
public static void main(String args[])throws IOException
//Register server on port 1234
{
ServerSocket ss= new ServerSocket(1234);//wait and accept a connection
Socket cs=ss.accept();//get a communication stream associated with the socket
Scanner ins =new Scanner(cs.getInputStream());
PrintWriter outs= new PrintWriter(cs.getOutputStream(),true);//perform
String s=ins.nextLine();
System.out.println("hello client:"+s);
outs.println("hello clint");//close stream and connection
outs.close();
ins.close();
cs.close();
ss.close();
}
}
Comments
Post a Comment