lOMoARcPSD| 59595715
Chương 4: Lập trình mạng trong Java
lOMoARcPSD| 59595715
Chư ng 3
1. Socket trong java
Java hỗ trợ lập trình mạng thông qua các lớp trong gói java.net. Một số gói tiêu
biểu
- InetAddress: Quản lý ịa chỉ internet bao gồm ịa chỉ IP và tên máy
- Socket: hỗ trphương thức liên quan tới socket cho chương trình client ở
chế ộ có kết nối
- ServerSocket: hỗ trphương thức liên quan tới socket cho chương trình
Server ở chế ộ có kết nối
- DatagramSocket: hỗ trợ các phương thức liên quan tới socket ở cả client
và server ở chế ộ không kết nối
- DatagramPacket: cài ặt gói tin dạng thư tín người dùng trong giao tiếp
client server ở chế ộ không kết nối
lOMoARcPSD| 59595715
Chư ng 3
- URL
- URLConnection
1. Socket trong java
Lớp InetAddress
Class mô tả về a chỉ IP (Internet Protocol)
– Các phư ng thức getLocalHost, getByName, hay getAllByName ể tạo một
InetAddress instance:
public static InetAddess InetAddress.getByName(String hostname)
public static InetAddess [] InetAddress.getAllByName(String
hostname)
public static InetAddess InetAddress.getLocalHost()
– Để lấy ịa chỉ IP hay tên dùng các phư ng thức:
getHostAddress() getHostName()
lOMoARcPSD| 59595715
Chư ng 3
1. Socket trong java
Lớp InetAddress
Ví dụ: In ịa chỉ IP của localhost
import java.net.*; public class
HostInfo { public static void
main(String args[]) { HostInfo host =
new HostInfo(); host.init();
}
public void init() {
try {
InetAddress myHost = InetAddress.getLocalHost();
System.out.println(myHost.getHostAddress());
System.out.println(myHost.getHostName());
} catch (UnknownHostException ex) {
System.err.println("Cannot find local host");
}
}
}
lOMoARcPSD| 59595715
Chư ng 3
1. Socket trong java
Lớp InetAddress
Ví dụ: In ịa chỉ IP của yahoo.com
import java.net.*; class indiachi{
public static void main (String args[]) {
try {
InetAddress[] addresses =
InetAddress.getAllByName(“yahoo.com");
for (int i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]);
}
}
catch (UnknownHostException e) {
System.out.println("Could not find yahoo.com");
}
}
}
lOMoARcPSD| 59595715
Chư ng 3
1. Socket trong java
Lớp Socket
Class mô tả về socket
Tạo một socket
Socket(InetAddress address, int port)
Socket(String host, int port)
Socket(InetAddress address, int port, InetAddress, localAddr, int
localPort)
Socket(String host, int port, InetAddress, localAddr, int localPort)
Socket()
Lấy thông tin về một socket
InetAddress getInetAddress() : trả về a chỉ mà socket kết nối
ến. int getPort() : trả về port mà socket kết nối ến. InetAddress
getLocalAddress() : trả về a chỉ cục bộ. int getLocalPort() : trả về
port cục bộ.
lOMoARcPSD| 59595715
Chư ng 3
1. Socket trong java
Lớp Socket
- Sử dụng Streams public OutputStream getOutputStream() throws
IOException Trả về một output stream cho việc viết các byte ến socket
này. public InputStream getInputStream() throws IOException Trả về
một input stream cho việc ọc các byte từ socket này.
1. Socket trong java
Lớp Socket, ví dụ kết nối tới một server
import java.net.*; import java.io.*; public
class getSocketInfo { public static void
main(String[] args) { for (int i = 0; i <
args.length; i++) { try {
Socket theSocket = new Socket(args[i], 80);
System.out.println("Connected to " +
theSocket.getInetAddress() + " on port " + theSocket.getPort() + " from port "
lOMoARcPSD| 59595715
Chư ng 3
+ theSocket.getLocalPort() + " of " + theSocket.getLocalAddress());
} catch (UnknownHostException e) {
System.err.println("I can't find " + args[i]);
} catch (SocketException e) {
System.err.println("Could not connect to " + args[i]);
} catch (IOException e) {
System.err.println(e);
}
} // end for
} // end main
} // end getSocketInfo
1. Socket trong java
Lớp ServerSocket
Class mô tả về ServerSocket
Tạo một ServerSocket
ServerSocket(int port) throws IOException
ServerSocket(int port, int backlog) throws IOException
lOMoARcPSD| 59595715
Chư ng 3
ServerSocket(int port, int backlog, InetAddress bindAddr)
throws
IOException
Các phư ng thức trong ServerSocket
Socket accept() throws IOException : Lắng nghe một kết nối ến
socket này và chấp nhận nó.
void close() throws IOException : Đóng socket.
InetAddress getInetAddress() : trả về ịa chỉ cục bộ của
socket int getLocalPort() : Trả về port mà server ang lắng
nghe. void setSoTimeout(int timeout) throws SocketException
1. Socket trong java
Lập trình Socket với UDP
Cung cấp cơ chế truyền không tin cậy giữa các nhóm các byte
(datagrams) giữa client và server.
Không cần thiết lập kết nối giữa client và server.
Sender phải gởi kèm ịa chỉ IP và port ích
lOMoARcPSD| 59595715
Chư ng 3
Server khi nhận dữ liệu sẽ phân tích ịa chỉ của sender ể truyền lại.
Có thể server chấp nhận nhiều client tại một thời iểm.
Chư ng 3
1. Socket trong java
Ví dụ lập trình Socket với UDP
Server (running on
hostid
)
create socket,
port=x, for
incoming request:
serverSocket
=
DatagramSoc
ket()
Client
create socket,
clientSocket =
DatagramSocket()
Create, address (hostid, port= x,
send datagram
request
read request fromusing clientSocket
serverSocket write reply to
serverSocket
client
read reply from
specifying
Chư ng 3
1. Socket trong java
host address,
clientSocket
port umber close
clientSocket
Ví dụ lập trình Socket với UDP
UDPClient.java
import java.io.*; import
java.net.*;
class UDPClient { public static void main(String args[])
throws Exception
{
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
Chư ng 3
1. Socket trong java
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("hostname");
byte[] sendData = new byte[1024]; byte[]
receiveData = new byte[1024]; String
sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Ví dụ lập trình Socket với UDP
UDPClient.java
Chư ng 3
1. Socket trong java
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new
String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
Chư ng 3
1. Socket trong java
Ví dụ lập trình Socket với UDP
UDPServer.java
import java.io.*; import
java.net.*;
class UDPServer { public static void main(String args[])
throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
Chư ng 3
1. Socket trong java
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
Ví dụ lập trình Socket với UDP
UDPServer.java
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
Chư ng 3
1. Socket trong java
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
lOMoARcPSD| 59595715
Chư ng 3
1. Socket trong java
Lập trình Socket với TCP
Server
Server process phải chạy trước.
Server phải tạo một socket ể lắng nghe và chấp nhận các kết nối từ
client.
Client
Khởi tạo TCP socket.
Xác ịnh IP address, port number của server.
Thiết lập kết ni ến server.
Khi server nhận yêu cầu kết nối, nó sẽ chấp nhận yêu cầu và khởi tạo
socket mới ể giao tiếp với client.
Có thể server chấp nhận nhiều client tại một thời iểm.
Ví dụ lập trình Socket với TCP
Server (running on
hostid
) Client
lOMoARcPSD| 59595715
Chư ng 3
1. Socket trong java
create socket,
port=x, for
incoming request:
welcomeSocket = ServerSocket()
TCP
create socket,
wait for incoming
connection request
connection setup connect to hostid, port=x connectionSocket
=
clientSocket =
welcomeSocket.accept()
Socket()
send request
using
read request fromclientSocket
connectionSocket
write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
lOMoARcPSD| 59595715
Chư ng 3
1. Socket trong java
Ví dụ lập trình Socket với TCP
TCPClient.java import
java.io.*; import java.net.*;
class TCPClient { public static void main(String argv[])
throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
Socket clientSocket = new Socket("hostname", 6789);
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());

Preview text:

lOMoAR cPSD| 59595715
Chương 4: Lập trình mạng trong Java lOMoAR cPSD| 59595715 Chư ng 3 1. Socket trong java
Java hỗ trợ lập trình mạng thông qua các lớp trong gói java.net. Một số gói tiêu biểu -
InetAddress: Quản lý ịa chỉ internet bao gồm ịa chỉ IP và tên máy -
Socket: hỗ trợ phương thức liên quan tới socket cho chương trình client ở chế ộ có kết nối -
ServerSocket: hỗ trợ phương thức liên quan tới socket cho chương trình
Server ở chế ộ có kết nối -
DatagramSocket: hỗ trợ các phương thức liên quan tới socket ở cả client
và server ở chế ộ không kết nối -
DatagramPacket: cài ặt gói tin dạng thư tín người dùng trong giao tiếp
client server ở chế ộ không kết nối lOMoAR cPSD| 59595715 Chư ng 3 - URL - URLConnection 1. Socket trong java
Lớp InetAddress
Class mô tả về ịa chỉ IP (Internet Protocol)
– Các phư ng thức getLocalHost, getByName, hay getAllByName ể tạo một
InetAddress instance:
public static InetAddess InetAddress.getByName(String hostname)
public static InetAddess [] InetAddress.getAllByName(String hostname)
public static InetAddess InetAddress.getLocalHost()
– Để lấy ịa chỉ IP hay tên dùng các phư ng thức:
getHostAddress() getHostName() lOMoAR cPSD| 59595715 Chư ng 3 1. Socket trong java
Lớp InetAddress
Ví dụ: In ịa chỉ IP của localhost
import java.net.*; public class
HostInfo { public static void
main(String args[]) { HostInfo host =
new HostInfo(); host.init();
}
public void init() { try {
InetAddress myHost = InetAddress.getLocalHost();
System.out.println(myHost.getHostAddress());
System.out.println(myHost.getHostName());
} catch (UnknownHostException ex) {
System.err.println("Cannot find local host");
} } } lOMoAR cPSD| 59595715 Chư ng 3 1. Socket trong java
Lớp InetAddress
Ví dụ: In ịa chỉ IP của yahoo.com
import java.net.*; class indiachi{
public static void main (String args[]) { try {
InetAddress[] addresses =
InetAddress.getAllByName(“yahoo.com");
for (int i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]); } }
catch (UnknownHostException e) {
System.out.println("Could not find yahoo.com"); } } } lOMoAR cPSD| 59595715 Chư ng 3 1. Socket trong java
Lớp Socket
Class mô tả về socket
– Tạo một socket
Socket(InetAddress address, int port)
Socket(String host, int port)
Socket(InetAddress address, int port, InetAddress, localAddr, int localPort)
Socket(String host, int port, InetAddress, localAddr, int localPort) Socket()
– Lấy thông tin về một socket
InetAddress getInetAddress() : trả về
ịa chỉ mà socket kết nối
ến. int getPort() : trả về port mà socket kết nối ến. InetAddress
getLocalAddress() : trả về ịa chỉ cục bộ. int getLocalPort() : trả về port cục bộ.
lOMoAR cPSD| 59595715 Chư ng 3 1. Socket trong java
Lớp Socket
- Sử dụng Streams public OutputStream getOutputStream() throws
IOException Trả về một output stream cho việc viết các byte ến socket
này. public InputStream getInputStream() throws IOException Trả về
một input stream cho việc ọc các byte từ socket này. 1. Socket trong java
Lớp Socket, ví dụ kết nối tới một server
import java.net.*; import java.io.*; public
class getSocketInfo { public static void
main(String[] args) { for (int i = 0; i <
args.length; i++) { try {

Socket theSocket = new Socket(args[i], 80);
System.out.println("Connected to " +
theSocket.getInetAddress() + " on port " + theSocket.getPort() + " from port " lOMoAR cPSD| 59595715 Chư ng 3
+ theSocket.getLocalPort() + " of " + theSocket.getLocalAddress());
} catch (UnknownHostException e) {
System.err.println("I can't find " + args[i]);
} catch (SocketException e) {
System.err.println("Could not connect to " + args[i]);
} catch (IOException e) {
System.err.println(e); } } // end for } // end main
} // end getSocketInfo 1. Socket trong java
Lớp ServerSocket

– Class mô tả về ServerSocket
– Tạo một ServerSocket
ServerSocket(int port) throws IOException
ServerSocket(int port, int backlog) throws IOException lOMoAR cPSD| 59595715 Chư ng 3
ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException
– Các phư ng thức trong ServerSocket
Socket accept() throws IOException : Lắng nghe một kết nối ến
socket này và chấp nhận nó.
void close() throws IOException : Đóng socket.
InetAddress getInetAddress() : trả về
ịa chỉ cục bộ của
socket int getLocalPort() : Trả về port mà server ang lắng
nghe. void setSoTimeout(int timeout) throws SocketException
1. Socket trong java
Lập trình Socket với UDP
 Cung cấp cơ chế truyền không tin cậy giữa các nhóm các byte
(datagrams) giữa client và server.
 Không cần thiết lập kết nối giữa client và server.
 Sender phải gởi kèm ịa chỉ IP và port ích lOMoAR cPSD| 59595715 Chư ng 3
 Server khi nhận dữ liệu sẽ phân tích ịa chỉ của sender ể truyền lại.
 Có thể server chấp nhận nhiều client tại một thời iểm. Chư ng 3 1. Socket trong java
Ví dụ lập trình Socket với UDP serverSocket = DatagramSoc
Server (running on hostid) ket() Client create socket, port=x, for incoming request: create socket, clientSocket = DatagramSocket()
Create, address (hostid, port= x, send datagram request
read request fromusing clientSocket serverSocket write reply to serverSocket specifying clientread reply from Chư ng 3 1. Socket trong java host address, clientSocket port umber close clientSocket
Ví dụ lập trình Socket với UDP UDPClient.java import java.io.*; import java.net.*;
class UDPClient { public static void main(String args[]) throws Exception {
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in)); Chư ng 3 1. Socket trong java
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("hostname");
byte[] sendData = new byte[1024]; byte[]
receiveData = new byte[1024]; String
sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Ví dụ lập trình Socket với UDP UDPClient.java Chư ng 3 1. Socket trong java
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);

DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket); String modifiedSentence = new
String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } Chư ng 3 1. Socket trong java
Ví dụ lập trình Socket với UDP UDPServer.java import java.io.*; import java.net.*;
class UDPServer { public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024]; while(true) { Chư ng 3 1. Socket trong java
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
Ví dụ lập trình Socket với UDP UDPServer.java
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes(); Chư ng 3 1. Socket trong java
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, port);
serverSocket.send(sendPacket); } } } lOMoAR cPSD| 59595715 Chư ng 3 1. Socket trong java
Lập trình Socket với TCP Server
– Server process phải chạy trước.
– Server phải tạo một socket ể lắng nghe và chấp nhận các kết nối từ client. Client – Khởi tạo TCP socket.
– Xác ịnh IP address, port number của server.
– Thiết lập kết nối ến server.
Khi server nhận yêu cầu kết nối, nó sẽ chấp nhận yêu cầu và khởi tạo
socket mới ể giao tiếp với client.
– Có thể server chấp nhận nhiều client tại một thời iểm.
Ví dụ lập trình Socket với TCP Server (running on hostid) Client lOMoAR cPSD| 59595715 Chư ng 3 1. Socket trong java create socket, port=x, for incoming request:
welcomeSocket = ServerSocket() TCP
create socket, wait for incoming connection request
connection setup connect to hostid, port=x connectionSocket =
clientSocket = welcomeSocket.accept() Socket() send request using read request fromclientSocket connectionSocket write reply to connectionSocket read reply from clientSocket close connectionSocket close clientSocket lOMoAR cPSD| 59595715 Chư ng 3 1. Socket trong java
Ví dụ lập trình Socket với TCP TCPClient.java import java.io.*; import java.net.*;
class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
Socket clientSocket = new Socket("hostname", 6789);
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());