- Sản phẩm & Dịch vụSản phẩm & Dịch vụ
- Giải phápGiải pháp
- Bảng giáBảng giá
- Công tyCông ty
- Tài liệuTài liệu
vi
vi
Chuyên mục với các bài viết hướng dẫn, nghiên cứu và phân tích chi tiết về kỹ thuật, các xu hướng công nghệ mới nhất dành cho lập trình viên.
Web Developer
I’m passionate about web development and sharing my insights through articles, with over 8 years of experience. I hope these sharings inspire you and help build a strong web development community. @#@ Tôi đam mê phát triển web và chia sẻ những hiểu biết của mình thông qua các bài viết, với hơn 8 năm kinh nghiệm. Tôi hy vọng những chia sẻ này sẽ truyền cảm hứng cho các bạn và giúp xây dựng một cộng đồng phát triển web mạnh mẽ.
Thảo luận (0)
Đăng nhập để thảo luận
Mỗi server là một chương trình chạy trên một hệ thống và lắng nghe (listen) trên một port nhất định. Socket trong Java được gắn với các số port, và khi ta chạy bất kỳ server nào, nó sẽ lắng nghe trên socket đó và chờ request từ client. Ví dụ, Tomcat server chạy trên port 8080 sẽ chờ các request từ client, và sẽ gửi lại phản hồi một khi nhận được request.

Socket là một điểm cuối (endpoint) trong một kênh giao tiếp hai chiều giữa hai chương trình chạy trên mạng. Socket được gắn với một số port để tầng TCP có thể xác định ứng dụng đích mà dữ liệu cần được gửi tới. Trong bài hướng dẫn này, chúng ta sẽ học cách viết chương trình socket server và socket client trong Java. Ta cũng sẽ tìm hiểu cách chương trình server và client đọc ghi dữ liệu trên socket. java.net.Socket và java.net.ServerSocket là các class trong Java dùng để triển khai socket và socket server.
Ví dụ chương trình socket server:
package com.journaldev.socket;import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.ClassNotFoundException; import java.net.ServerSocket; import java.net.Socket;
/**
*/ public class SocketServerExample {
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 9876;
public static void main(String args[]) throws IOException, ClassNotFoundException{
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for the client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//write object to Socket
oos.writeObject("Hi Client "+message);
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
}
Ví dụ chương trình socket client:
package com.journaldev.socket;import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException;
/**
*/ public class SocketClientExample {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException{
//get the localhost IP address, if server is running on some other IP, you need to use that
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
for(int i=0; i<5;i++){
//establish socket connection to server
socket = new Socket(host.getHostName(), 9876);
//write to socket using ObjectOutputStream
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Sending request to Socket Server");
if(i==4)oos.writeObject("exit");
else oos.writeObject(""+i);
//read the server response message
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
//close resources
ois.close();
oos.close();
Thread.sleep(100);
}
}
}
Để kiểm tra giao tiếp server-client giữa hai chương trình trên, trước tiên ta cần khởi chạy server. Khi đó, chương trình sẽ chỉ in ra dòng chữ “Waiting for client request” và sau đó dừng lại để chờ request từ client.
Tiếp theo, khi ta chạy class SocketClientExample, nó sẽ gửi một request đến socket server và in thông báo phản hồi ra dòng lệnh. Dưới đây là output của chương trình socket server.
Waiting for the client request Message Received: 0 Waiting for the client request Message Received: 1 Waiting for the client request Message Received: 2 Waiting for the client request Message Received: 3 Waiting for the client request Message Received: exit Shutting down Socket server!!
Còn đây là output từ chương trình Java socket client.
Sending request to Socket Server Message: Hi Client 0 Sending request to Socket Server Message: Hi Client 1 Sending request to Socket Server Message: Hi Client 2 Sending request to Socket Server Message: Hi Client 3 Sending request to Socket Server Message: Hi Client exit
Với những kiến thức nền tảng về lập trình socket trong Java vừa được trình bày, hy vọng bạn đã có cái nhìn tổng quan để khởi tạo các ứng dụng giao tiếp mạng đơn giản. Để đi sâu hơn và nắm vững kỹ thuật này, hãy tham khảo thêm tài liệu chính thức từ Oracle.