Java - A Simple Client Server Connection

This code snippet demonstrates a simple client/server connection. There is no communication between the client and the server. The purpose of this code is to demonstrate the connection at its simplest. Notice that the server accepts clients in an infinite loop so that it can accept multiple clients.

Client

  1. import java.net.*;  
  2. import java.io.*;  
  3.   
  4. class Client{  
  5.   
  6.     public static void main(String args[]){  
  7.         System.out.println( "Connecting to server");  
  8.           
  9.         try {  
  10.             Socket skClient = new Socket( "127.0.0.1", 1234);  
  11.               
  12.             System.out.println( "Connected to server!!!");  
  13.               
  14.         }  
  15.         catch (Exception e){  
  16.             System.out.println(e.getMessage());  
  17.         }  
  18.     }  
  19. }  

Server

  1. import java.net.*;  
  2. import java.io.*;  
  3.   
  4. class Server{  
  5.   
  6.     public static void main(String args[]){  
  7.           
  8.         try {  
  9.             ServerSocket skServer = new ServerSocket(1234);  
  10.               
  11.             System.out.println( "Server started");  
  12.           
  13.             while (true){  
  14.                 Socket skClient = skServer.accept();  
  15.             }  
  16.               
  17.         }  
  18.         catch (Exception e){  
  19.             System.out.println(e.getMessage());  
  20.         }  
  21.     }  
  22. }  

No comments:

Post a Comment