Network Socket – Part 2


Tiếp theo bài SOCKET basic kia …mình làm 1 bài tương tự nhưng Server có thể giao tiếp với nhiều Client trong tại 1 thời điểm. Tuy vậy cách này vẫn không đảm bảo….vẫn có trường hợp Race khi 2 Client cùng 1 lúc giao tiếp với server. Nhưng đây là cách đơn giản mà chúng ta thể hiển một chương trình . 1 Server – N Client

Client chúng ta như sau :

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ClientA {
	public static void main(String[] args) {
		// initialize Client and connect to server with port 9999
		ClientA myClient = new ClientA();
		myClient.connectServer("127.0.0.1", 8989);

	}

	public void connectServer(String server, int port){
		try {
			// Make a socket connection to whatever is running on server - port
			Socket s = new Socket(server, port);

			// send data to server
			PrintWriter writer = new PrintWriter(s.getOutputStream(),true);
			String message = "";
			Scanner sc = new Scanner(System.in);
			while(true){
				message = sc.nextLine();
				if(message.equals("close"))
					break;
				writer.println("Client 1 : " + message);
			}
			writer.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

Server của chúng ta :

package com.gcs.server;

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 java.util.ArrayList;

public class Server {

	public static void main(String[] args) {
		Server myServer = new Server();
		myServer.publicServer();
	}

	public void publicServer(){
		try {
			// ServerSocket make this server application listen for client request
			// on port 4242 while(true) to listening continuous
			ServerSocket serverSocket = new ServerSocket(8989);
			System.out.println("Server start connect.....");
			while(true){
				// listening.....
				Socket sock = serverSocket.accept();
				// we create thread to handler message from client
				Thread t = new Thread(new HandlerClient(sock));
				t.start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public class HandlerClient implements Runnable{
		BufferedReader reader;
		Socket socketClient;

		// we initialize BufferedReader to get message from client
		public HandlerClient(Socket socketClient) {
			try {
				this.socketClient = socketClient;
				reader = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// get communication maintain to when mess="close" .
		public void run() {
			String message = "";
			try {
				while(true){
					message = reader.readLine();
					if(!message.equalsIgnoreCase("close")){
						System.out.println(message);

					}
					else{
						System.out.println("Client Close....");
						break;
					}
				}
			} catch (Exception e) {}

		}

	}
}

1 – Chúng ta Start Server lên
2 – Chúng ta mở command line để biên dịch và run client.

kết quả đơn giản chúng ta có thể thấy như sau :
d1

Hy vọng help các chú =]]….

Leave a comment