RSS

Create TCP socket

07 Jan

Today, I’ll show you how to create TCP socket in Java. We can see more in:

The first, TCP socket often using client/Server topology. Server will open a socket and listen connection from other stations.  Creating TCP socket need two important things: One Server socket listening in static port, Clients connected to server that has static port and static IP ( static public IP with Internet)

 

Creating Server Socket ( listening):

Using class ServerSocket in java.net.ServerSocket package to create socket listening from client. Syntax:

ServerSocket serverSock = new ServerSocket(PORT_CHAT,MAX_USER_WAITING);

PORT_CHAT is port that to be client use to connected.

MAX_USER_WAITING is amount of user that waiting server agree connection in the current time.

Because server always listen clients in the real time. So, server socket have to implement class Thread to listening client in the real time

public class Server extends Thead {

public void run(){

while (true){

… // main code listening

}

}

}

Because this is network communication then maybe  throw some exception connection fall. So, we need to block it in try {} catch{} function.

Note:

We need to create local stream input and output to using in other method in class.

Variable reader and writer are stream input and output to client and server communicate with together

 

Full code example:

 

Creating Client Socket (connecting):

Easy than server. Client just only create socket and connect to server and communicate. We can see code example:

ServerElement:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* class extends Thread. Use to listen request after account finish the sign in
* @author freeloop
*/
public class ServerElement extends Thread{
    Socket sock;
    BufferedReader reader;
    PrintWriter writer;
    /**
     *  Initialization the value and run this thread
     */
    public ServerElement(Socket Sock){
        sock = Sock;
        try {
            reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            writer = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()),true);
            this.start();
        } catch (Exception e) {
        }
    }
    @Override
    public void run() {
        while(true){
            try {
                String read = reader.readLine();
                // waiting message from client ->work anything
                // example: print message
                System.out.println(read);
                writer.write("Hi! I had got message from you");

            } catch (IOException ex) {
                Logger.getLogger(ServerElement.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

Server:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;


public class Server extends Thread{

private ServerSocket serverSock;

private int PORT_CHAT;

private int MAX_USER_WAITING;

public Server() {

PORT_CHAT = 1990; // STATIC PORT FOR CLIENT CONNECT

MAX_USER_WAITING = 1000; // MAX USER WAITING CONNECT

try {

serverSock = new ServerSocket(PORT_CHAT, MAX_USER_WAITING);

this.start();

} catch (IOException ex) {

System.out.println("Don't create server sock room . ");

}

}

public void run() {

while (true){

try {

Socket accept = serverSock.accept();

synchronized(accept){

BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream()));

PrintWriter writer = new PrintWriter(new OutputStreamWriter(accept.getOutputStream() ),true);

/*

* We need to execute main for client in other thread. Therefore, Server thread

* will release so fast. Many clients requested

*/

new ServerElement(accept);

}

}

catch (Exception e){

System.out.println(e.getMessage());

e.printStackTrace();

}

}

}

}

Client:

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.Proxy;

import java.net.Socket;

import java.net.UnknownHostException;

import java.util.logging.Level;

import java.util.logging.Logger;


public class Client extends Thread{

private Socket sock_Listen;

private BufferedReader reader;

private PrintWriter writer;

public Client(){

try {

sock_Listen = new Socket("localhost", 1990);

reader = new BufferedReader(new InputStreamReader(sock_Listen.getInputStream()));

writer = new PrintWriter(new OutputStreamWriter(sock_Listen.getOutputStream()), true);

this.start();

// sending some thing to server

writer.write("Hello server. I'm client");


} catch (Exception ex) {

System.exit(0);

}

}

@Override

public void run() {

while (true){

try {

String read = reader.readLine();

// waiting message from server ->work anything

// example: print message

System.out.println(read);

} catch (IOException ex) {

//TODO de phong khong mat connect giua chung

System.exit(0);

}

}

}

}

Good luck for you!!!

Written by hotdream1990 

 

 
1 Comment

Posted by on January 7, 2011 in Java

 

Tags: ,

One response to “Create TCP socket

  1. ip camera

    January 11, 2011 at 1:43 pm

    A truly beneficial publish by you my good friend. We have bookmarked this web page and can are available back again following several days to verify for almost any new posts that you just make.

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s