Chat LIVE With Programming Experts! There Are 23 Online Right Now...

 

Code Snippets

  

Java Source Code


Welcome to Dream.In.Code
Become a Java Expert!

Join 244,258 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,288 people online right now. Registration is fast and FREE... Join Now!





TCP/IP Client and Server

A simple Client/Server demo program. The server waits for connection and starts a thread when there is a connection request from a client. The server receives a String from the client and returns it to the client in uppercase.

Submitted By: pbl
Actions:
Rating:
Views: 6,927

Language: Java

Last Modified: April 28, 2008
Instructions: The client connects to the server specifying "localhost". That means the server and the client are on the same system.
The port 1500 is used for communication.

Snippet


  1. //The server code Server.java:
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5.  
  6. /**
  7. * This is to help people to write Client server application
  8. *  I tried to make it as simple as possible... the client connect to the server
  9. *  the client send a String to the server the server returns it in UPPERCASE thats all
  10. */
  11. public class Server {
  12.  
  13.         // the socket used by the server
  14.         private ServerSocket serverSocket;
  15.         // server constructor
  16.         Server(int port) {
  17.                
  18.                 /* create socket server and wait for connection requests */
  19.                 try
  20.                 {
  21.                         serverSocket = new ServerSocket(port);
  22.                         System.out.println("Server waiting for client on port " + serverSocket.getLocalPort());
  23.  
  24.                         while(true)
  25.                         {
  26.                                 Socket socket = serverSocket.accept()// accept connection
  27.                                 System.out.println("New client asked for a connection");
  28.                                 TcpThread t = new TcpThread(socket);    // make a thread of it
  29.                                 System.out.println("Starting a thread for a new Client");
  30.                                 t.start();
  31.                         }
  32.                 }
  33.                 catch (IOException e) {
  34.                         System.out.println("Exception on new ServerSocket: " + e);
  35.                 }
  36.         }               
  37.  
  38. //        you must "run" server to have the server run as a console application
  39.         public static void main(String[] arg) {
  40.                 // start server on port 1500
  41.                 new Server(1500);
  42.         }
  43.        
  44.         /** One instance of this thread will run for each client */
  45.         class TcpThread extends Thread {
  46.                 // the socket where to listen/talk
  47.                 Socket socket;
  48.                 ObjectInputStream Sinput;
  49.                 ObjectOutputStream Soutput;
  50.                
  51.                 TcpThread(Socket socket) {
  52.                         this.socket = socket;
  53.                 }
  54.                 public void run() {
  55.                         /* Creating both Data Stream */
  56.                         System.out.println("Thread trying to create Object Input/Output Streams");
  57.                         try
  58.                         {
  59.                                 // create output first
  60.                                 Soutput = new ObjectOutputStream(socket.getOutputStream());
  61.                                 Soutput.flush();
  62.                                 Sinput  = new ObjectInputStream(socket.getInputStream());
  63.                         }
  64.                         catch (IOException e) {
  65.                                 System.out.println("Exception creating new Input/output Streams: " + e);
  66.                                 return;
  67.                         }
  68.                         System.out.println("Thread waiting for a String from the Client");
  69.                         // read a String (which is an object)
  70.                         try {
  71.                                 String str = (String) Sinput.readObject();
  72.                                 str = str.toUpperCase();
  73.                                 Soutput.writeObject(str);
  74.                                 Soutput.flush();
  75.                         }
  76.                         catch (IOException e) {
  77.                                 System.out.println("Exception reading/writing  Streams: " + e);
  78.                                 return;                               
  79.                         }
  80.                         // will surely not happen with a String
  81.                         catch (ClassNotFoundException o) {                               
  82.                         }
  83.                         finally {
  84.                                 try {
  85.                                         Soutput.close();
  86.                                         Sinput.close();
  87.                                 }
  88.                                 catch (Exception e) {                                       
  89.                                 }
  90.                         }
  91.                 }
  92.         }
  93. }
  94.  
  95.  
  96. //The client code Client.java:
  97.  
  98.  
  99. import java.net.*;
  100. import java.io.*;
  101.  
  102. public class Client {
  103.  
  104.         ObjectInputStream Sinput;                // to read the socker
  105.         ObjectOutputStream Soutput;        // towrite on the socket
  106.         Socket socket;
  107.  
  108.         // Constructor connection receiving a socket number
  109.         Client(int port) {
  110.                 // we use "localhost" as host name, the server is on the same machine
  111.                 // but you can put the "real" server name or IP address
  112.                 try {
  113.                         socket = new Socket("localhost", port);
  114.                 }
  115.                 catch(Exception e) {
  116.                         System.out.println("Error connectiong to server:" + e);
  117.                         return;
  118.                 }
  119.                 System.out.println("Connection accepted " +
  120.                                 socket.getInetAddress() + ":" +
  121.                                 socket.getPort());
  122.  
  123.                 /* Creating both Data Stream */
  124.                 try
  125.                 {
  126.                         Sinput  = new ObjectInputStream(socket.getInputStream());
  127.                         Soutput = new ObjectOutputStream(socket.getOutputStream());
  128.                 }
  129.                 catch (IOException e) {
  130.                         System.out.println("Exception creating new Input/output Streams: " + e);
  131.                         return;
  132.                 }
  133.                 // now that I have my connection
  134.                 String test = "aBcDeFgHiJkLmNoPqRsTuVwXyZ";
  135.                 // send the string to the server
  136.                 System.out.println("Client sending \"" + test + "\" to serveur");
  137.                 try {
  138.                         Soutput.writeObject(test);
  139.                         Soutput.flush();
  140.                 }
  141.                 catch(IOException e) {
  142.                         System.out.println("Error writting to the socket: " + e);
  143.                         return;
  144.                 }
  145.                 // read back the answer from the server
  146.                 String response;
  147.                 try {
  148.                         response = (String) Sinput.readObject();
  149.                         System.out.println("Read back from server: " + response);
  150.                 }
  151.                 catch(Exception e) {
  152.                         System.out.println("Problem reading back from server: " + e);
  153.                 }
  154.                
  155.                 try{
  156.                         Sinput.close();
  157.                         Soutput.close();
  158.                 }
  159.                 catch(Exception e) {}
  160.         } 
  161.  
  162.         public static void main(String[] arg) {
  163.                 new Client(1500);
  164.         }
  165. }
  166.  

Copy & Paste


Comments


prajayshetty 2008-06-13 12:20:45

thats a nice for learning socketing in java

nuhajat 2008-07-01 12:26:55

Graet!! it`s nice but i`m newbie.. Would u like to help me.. make "Billing Internet Cafe" Aplication please...

kamran_mrz 2009-03-10 16:11:08

hi,it is good but i need a http web browser ,web broser must dont use component and should be simple please help me Zolfaghary@inbox.com

cjdalley 2009-04-24 20:12:25

Perfect example! Thank you very much I've been looking for something like this for weeks!

Rose Smile 2009-05-06 13:44:54

Thank you very much I got a great benifit from it Best regards ..


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month