Socket trong Java là gì? Cách sử dụng và ví dụ cụ thể
3 phút đọc09/07/2025
Bao Tran
Web Developer
0 lượt xem
0 lượt xem
Reading Time: 3minutes
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.
Lập trình socket trong Java
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;
/**
* This class implements java Socket server
* @author pankaj
*
*/
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;
/**
* This class implements java socket client
* @author pankaj
*
*/
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
Tổng kết
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.
Về tác giả
Bao TranWeb 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ẽ.
Cập nhật thông tin mới nhấtNhận các thông tin mới nhất về mối đe dọa, báo cáo an ninh mạng từ CyStack về hòm thư điện tử của bạn
Thảo luận (0)
Đăng nhập để thảo luận
Bài viết liên quan
{"success":true,"head":"<title>Socket trong Java là gì? Cách sử dụng và ví dụ cụ thể - CyStack Tutorial</title>\n<meta name=\"description\" content=\"Hãy tham khảo ví dụ lập trình socket trong Java trong bài viết này, bao gồm cả triển khai socket server và client, để học cách thiết lập kết nối, gửi và nhận dữ liệu tương tác hai chiều.\"/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-video-preview:-1, max-image-preview:large\"/>\n<link rel=\"canonical\" href=\"https://blog.cystack.org/tutorial/2025/07/09/socket-trong-java-la-gi/\" />\n<meta property=\"og:locale\" content=\"en_US\" />\n<meta property=\"og:type\" content=\"article\" />\n<meta property=\"og:title\" content=\"Socket trong Java là gì? Cách sử dụng và ví dụ cụ thể - CyStack Tutorial\" />\n<meta property=\"og:description\" content=\"Hãy tham khảo ví dụ lập trình socket trong Java trong bài viết này, bao gồm cả triển khai socket server và client, để học cách thiết lập kết nối, gửi và nhận dữ liệu tương tác hai chiều.\" />\n<meta property=\"og:url\" content=\"https://blog.cystack.org/tutorial/2025/07/09/socket-trong-java-la-gi/\" />\n<meta property=\"og:site_name\" content=\"CyStack Tutorial\" />\n<meta property=\"article:tag\" content=\"vi\" />\n<meta property=\"article:section\" content=\"Java\" />\n<meta property=\"og:updated_time\" content=\"2025-07-18T15:27:55+07:00\" />\n<meta property=\"og:image\" content=\"https://s2.cystack.net/tutorial/09160435/lap-trinh-socket-trong-java.jpg\" />\n<meta property=\"og:image:secure_url\" content=\"https://s2.cystack.net/tutorial/09160435/lap-trinh-socket-trong-java.jpg\" />\n<meta property=\"og:image:width\" content=\"1200\" />\n<meta property=\"og:image:height\" content=\"630\" />\n<meta property=\"og:image:alt\" content=\"Lập trình Socket trong Java\" />\n<meta property=\"og:image:type\" content=\"image/jpeg\" />\n<meta property=\"article:published_time\" content=\"2025-07-09T16:18:39+07:00\" />\n<meta property=\"article:modified_time\" content=\"2025-07-18T15:27:55+07:00\" />\n<meta name=\"twitter:card\" content=\"summary_large_image\" />\n<meta name=\"twitter:title\" content=\"Socket trong Java là gì? Cách sử dụng và ví dụ cụ thể - CyStack Tutorial\" />\n<meta name=\"twitter:description\" content=\"Hãy tham khảo ví dụ lập trình socket trong Java trong bài viết này, bao gồm cả triển khai socket server và client, để học cách thiết lập kết nối, gửi và nhận dữ liệu tương tác hai chiều.\" />\n<meta name=\"twitter:image\" content=\"https://s2.cystack.net/tutorial/09160435/lap-trinh-socket-trong-java.jpg\" />\n<meta name=\"twitter:label1\" content=\"Written by\" />\n<meta name=\"twitter:data1\" content=\"Bao Tran\" />\n<meta name=\"twitter:label2\" content=\"Time to read\" />\n<meta name=\"twitter:data2\" content=\"3 minutes\" />\n<script type=\"application/ld+json\" class=\"rank-math-schema\">{\"@context\":\"https://schema.org\",\"@graph\":[{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https://blog.cystack.org/tutorial/#person\",\"name\":\"CyStack Tutorial\"},{\"@type\":\"WebSite\",\"@id\":\"https://blog.cystack.org/tutorial/#website\",\"url\":\"https://blog.cystack.org/tutorial\",\"name\":\"CyStack Tutorial\",\"publisher\":{\"@id\":\"https://blog.cystack.org/tutorial/#person\"},\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https://s2.cystack.net/tutorial/09160435/lap-trinh-socket-trong-java.jpg\",\"url\":\"https://s2.cystack.net/tutorial/09160435/lap-trinh-socket-trong-java.jpg\",\"width\":\"1200\",\"height\":\"630\",\"caption\":\"L\\u1eadp tr\\u00ecnh Socket trong Java\",\"inLanguage\":\"en-US\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https://blog.cystack.org/tutorial/2025/07/09/socket-trong-java-la-gi/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":\"1\",\"item\":{\"@id\":\"https://blog.cystack.org/tutorial\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"position\":\"2\",\"item\":{\"@id\":\"https://blog.cystack.org/tutorial/category/java/\",\"name\":\"Java\"}},{\"@type\":\"ListItem\",\"position\":\"3\",\"item\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/07/09/socket-trong-java-la-gi/\",\"name\":\"Socket trong Java l\\u00e0 g\\u00ec? C\\u00e1ch s\\u1eed d\\u1ee5ng v\\u00e0 v\\u00ed d\\u1ee5 c\\u1ee5 th\\u1ec3\"}}]},{\"@type\":\"WebPage\",\"@id\":\"https://blog.cystack.org/tutorial/2025/07/09/socket-trong-java-la-gi/#webpage\",\"url\":\"https://blog.cystack.org/tutorial/2025/07/09/socket-trong-java-la-gi/\",\"name\":\"Socket trong Java l\\u00e0 g\\u00ec? C\\u00e1ch s\\u1eed d\\u1ee5ng v\\u00e0 v\\u00ed d\\u1ee5 c\\u1ee5 th\\u1ec3 - CyStack Tutorial\",\"datePublished\":\"2025-07-09T16:18:39+07:00\",\"dateModified\":\"2025-07-18T15:27:55+07:00\",\"isPartOf\":{\"@id\":\"https://blog.cystack.org/tutorial/#website\"},\"primaryImageOfPage\":{\"@id\":\"https://s2.cystack.net/tutorial/09160435/lap-trinh-socket-trong-java.jpg\"},\"inLanguage\":\"en-US\",\"breadcrumb\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/07/09/socket-trong-java-la-gi/#breadcrumb\"}},{\"@type\":\"Person\",\"@id\":\"https://blog.cystack.org/tutorial/author/baotran/\",\"name\":\"Bao Tran\",\"url\":\"https://blog.cystack.org/tutorial/author/baotran/\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https://secure.gravatar.com/avatar/0cdd33c02ec4a531fcf557b9c1ccc276df0c69031b2382c959bcf335248e840c?s=96&d=mm&r=g\",\"url\":\"https://secure.gravatar.com/avatar/0cdd33c02ec4a531fcf557b9c1ccc276df0c69031b2382c959bcf335248e840c?s=96&d=mm&r=g\",\"caption\":\"Bao Tran\",\"inLanguage\":\"en-US\"}},{\"@type\":\"BlogPosting\",\"headline\":\"Socket trong Java l\\u00e0 g\\u00ec? C\\u00e1ch s\\u1eed d\\u1ee5ng v\\u00e0 v\\u00ed d\\u1ee5 c\\u1ee5 th\\u1ec3 - CyStack Tutorial\",\"keywords\":\"socket trong Java\",\"datePublished\":\"2025-07-09T16:18:39+07:00\",\"dateModified\":\"2025-07-18T15:27:55+07:00\",\"articleSection\":\"Java\",\"author\":{\"@id\":\"https://blog.cystack.org/tutorial/author/baotran/\",\"name\":\"Bao Tran\"},\"publisher\":{\"@id\":\"https://blog.cystack.org/tutorial/#person\"},\"description\":\"H\\u00e3y tham kh\\u1ea3o v\\u00ed d\\u1ee5 l\\u1eadp tr\\u00ecnh socket trong Java trong b\\u00e0i vi\\u1ebft n\\u00e0y, bao g\\u1ed3m c\\u1ea3 tri\\u1ec3n khai socket server v\\u00e0 client, \\u0111\\u1ec3 h\\u1ecdc c\\u00e1ch thi\\u1ebft l\\u1eadp k\\u1ebft n\\u1ed1i, g\\u1eedi v\\u00e0 nh\\u1eadn d\\u1eef li\\u1ec7u t\\u01b0\\u01a1ng t\\u00e1c hai chi\\u1ec1u.\",\"name\":\"Socket trong Java l\\u00e0 g\\u00ec? C\\u00e1ch s\\u1eed d\\u1ee5ng v\\u00e0 v\\u00ed d\\u1ee5 c\\u1ee5 th\\u1ec3 - CyStack Tutorial\",\"@id\":\"https://blog.cystack.org/tutorial/2025/07/09/socket-trong-java-la-gi/#richSnippet\",\"isPartOf\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/07/09/socket-trong-java-la-gi/#webpage\"},\"image\":{\"@id\":\"https://s2.cystack.net/tutorial/09160435/lap-trinh-socket-trong-java.jpg\"},\"inLanguage\":\"en-US\",\"mainEntityOfPage\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/07/09/socket-trong-java-la-gi/#webpage\"}}]}</script>\n"}