Java Socket Example

Categories: Java; Tagged with: ; @ April 2nd, 2013 0:43

Requirement:  Client send message to Server, Server get the message and return to Client.

Codes:

MesgServer:

package com.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import com.common.LogHelper;

/**
 * ServerSide: receive message from Client and return it. 
 * @author Guoliang
 *
 */
public class MesgServer implements Runnable{
	
	public void run() {
		LogHelper.log("ServerStarted");
		try {
			ServerSocket serverSocket = new ServerSocket(8888);
		
			while (true) {
				
					Socket socket = serverSocket.accept();
					LogHelper.log("Request: " + socket.toString());
					
					BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					PrintWriter out = new PrintWriter(socket.getOutputStream());
					
					out.println("Connected!");
					out.flush();
					
					String lineInput;
					while ((lineInput = in.readLine()) != null) {
						LogHelper.log("GotMesgFromClient: " + lineInput);
						out.println("ServerReturnMsg: " + lineInput);
						out.flush();
						if("exit".equals(lineInput)) {
							break;
						}
					}
					
					out.close();
					in.close();
					socket.close();
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

MesgClient

package com.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.common.LogHelper;

public class MesgClient {

	/**
	 * Send mesg to server side.
	 * @param args
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		// Start server. 
		new Thread(new MesgServer()).start();
		
		Socket socket = new Socket("localhost", 8888);
		LogHelper.log("Connecting...");
		
		PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        
        LogHelper.log(in.readLine());
        
        // Simplest testing
        out.println("Hello!"); 
        LogHelper.log(in.readLine());
        
        // Read user input.
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String strInput = null;
        while ((strInput = stdIn.readLine()) != null) {
        	out.println(strInput);
        	LogHelper.log("Send: " + strInput);
        	LogHelper.log(in.readLine());
		}
	}
}

Output:

[Thread-0]ServerStarted
[main]Connecting...
[Thread-0]Request: Socket[addr=/127.0.0.1,port=5569,localport=8888]
[main]Connected!
[Thread-0]GotMesgFromClient: Hello!
[main]ServerReturnMsg: Hello!
liguoliang.com  // user input.
[Thread-0]GotMesgFromClient: liguoliang.com
[main]Send: liguoliang.com
[main]ServerReturnMsg: liguoliang.com



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.