Wednesday 15 July 2015

Client Server Communication using TCP

TcpServer.java
  
         
import java.io.*;
import java.net.*;

public class TcpServer {

    public static void main(String[] args) throws IOException {
        //Open the Server Socket
        ServerSocket srv = new ServerSocket(1234);
        //Wait for the Client Request
        Socket skt = srv.accept();
        //Create I/O streams for communicating to the client
        OutputStream sout = skt.getOutputStream();
        DataOutputStream dout = new DataOutputStream(sout);
        //Perform communication with client
        dout.writeUTF("This is server Msg..!");
        //Close socket
        dout.close();
        sout.close();
        skt.close();
    }
}
        
  
TcpClient.java
  
         
import java.io.*;
import java.net.*;

public class TcpClient {

    public static void main(String[] args) throws IOException {
        //Create a Socket Object
        Socket skt = new Socket("localhost", 1234);
        //Create I/O streams for communicating with the server
        InputStream sin = skt.getInputStream();
        DataInputStream din = new DataInputStream(sin);
        //Perform I/O or communication with the server
        String str = new String(din.readUTF());
        System.out.println(str);
        //Close the socket when done
        din.close();
        sin.close();
        skt.close();
    }
}
        
  

No comments:

Post a Comment