Networking in Java

Server Program
import java.net.*;
import java.io.*;
class ServerDemo1{
    public static void main(String ar[])throws Exception{
        ServerSocket ss=new ServerSocket(1234);
        Socket clientSocket=ss.accept();
        InputStream in=clientSocket.getInputStream();
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
        OutputStream out=clientSocket.getOutputStream();
        while(true){
            String m=br.readLine();
            //if(m!=null && !(m.length()<1)){
                System.out.println("Data Recieved From Client \n"+m);
            //}
            out.write(m.toUpperCase().getBytes());
            out.write(13);
            out.write(10);
            out.flush();
        }
    }
}


Client Program
import java.net.*;
import java.io.*;
class ClientDemo1{
    public static void main(String ar[])throws Exception{
        Socket serverSocket=new Socket("localhost",1234);
        InputStream in=serverSocket.getInputStream();
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
        OutputStream out=serverSocket.getOutputStream();
        Console c=System.console();
        while(true){
            String msg=c.readLine("Enter Message to Server and \"q\" to stop  \n");
            if(msg.equals("q"))break;
            out.write(msg.getBytes());
            out.write(13);
            out.write(10);
            String m=br.readLine();
            System.out.println(m);
            out.flush();
        }
        
    }
}

No comments:

Popular Posts