Tải bản đầy đủ (.doc) (46 trang)

Tai lieu hoc tap tat ca cac mon

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (390.49 KB, 46 trang )

Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

Chương I – InetAddress
I, Khái Niệm :
- Lớp InetAddress được sử dụng để biểu diễn các địa chỉ IP trong một ứng dụng
mạng. Lớp này được sử dụng bởi hầu hết các lớp mạng, bao gồm Socket,
ServerSocket, DatagramSocket, DatagramPacket,…
- Nó bao gồm hai trường thông tin :
+ hostName (một đối tượng kiểu String)
+ address (một số kiểu int).
Các trường này không phải là trường public, vì thế ta không thể truy xuất chúng trực
tiếp.
- Mô tả mô hình khai báo đối tượng InetAddress :
public class InetAddress
{
private String hostName;
private int address;
public String getHostName()
{
return hostName;
}
...
};
- Ví dụ : Viết trang ThongTinMay để đọc các thông số về HostName, IP Address và
Domain Name của máy tính cục bộ đang làm việc :
import java.net.*;
class ThongTinMay
{
public static void main(String[] args)


{
try
{
InetAddress addr=InetAddress.getLocalHost();
String hostname=addr.getHostName();
String hostaddress=addr.getHostAddress();
String host=addr.getCanonicalHostName();
System.out.println("Host Name : " + hostname);
System.out.println("IP Address : " + hostaddress);
/>
-1-


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

System.out.println("Domain : " + host);
}
catch (UnknownHostException evt)
{
evt.printStackTrace();
}
}
}
Kết quả thu được như sau :

II, Phương Thức và Thuộc Tính
- Lớp InetAddress không có các hàm khởi tạo (constructor) . Tuy nhiên, có ba phương
thức tĩnh trả về các đối tượng thuộc kiểu InetAddress :

1, public static InetAddress InetAddress.getByName(String hostname)
Phương thức này được sử dụng để kết nối đến 1 máy chủ xác định, tham số truyền vào
là 1 chuỗi ký tự. Chuỗi này có thể là : tên máy, địa chỉ IP hoặc là địa chỉ 1 trang web…
2.
public static InetAddress[ ] InetAddress.getAllByName(String hostname)
kết quả trả về là 1 mảng đối tượng thuộc kiểu InetAddress
3. public static InetAddress InetAddress.getLocalHost()
phương thức này được sử dụng để đọc thông tin của máy cục bộ đang làm việc.
Ví dụ : Viết chương trình kết nối đến trang web “www.microsoft.com” , in ra màn
hình hostname và ip address của trang web đó :
import java.net.*;
class LayDC
{
public static void main(String[] args)
{
try
{
InetAddress dc =InetAddress.getByName("www.microsoft.com");
System.out.println("Dia Chi IP Trang Microsoft : " + dc);
/>
-2-


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

}
catch (UnknownHostException evt)
{

evt.printStackTrace();
}
}
}
Kết quả thu được như sau :

- Một số phương thức khác :
public String getHostName() :
Phương thức này trả về một chuỗi biểu diễn hostname của một đối tượng InetAddress.
Nếu máy không có hostname, thì nó sẽ trả về địa chỉ IP của máy này dưới dạng một
xâu ký tự.
public byte[ ] getAddress() :
Nếu bạn muốn biết địa chỉ IP của một máy, phương thức getAddress() trả về một địa
chỉ IP dưới dạng một mảng các byte.
Ví dụ : Viết chương trình đọc ra địa chỉ IP của máy tính, sau đó cho biết địa chỉ đó
nằm ở lớp địa chỉ nào :
import java.net.*;
class PhanLoaiIP
{
public static void main(String[] args) throws UnknownHostException
/>
-3-


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

{
InetAddress host=InetAddress.getLocalHost();

byte[] b=host.getAddress();
int i;
if (b[0]>=0)
i = b[0];
else
i = 256 + b[0];
if ( (i>=1) && (i<=126) )
System.out.println(host + " thuoc dia chi lop A");
if ( (i>=128) && (i<=191) )
System.out.println(host + " thuoc dia chi lop B");
if ( (i>=192) && (i<=223) )
System.out.println(host + " thuoc dia chi lop C");
}
}

Phụ lục tiếng Anh : Class InetAddress
Method Summary
boolean

equals(Object obj)
Compares this object against the specified object.

byte[]

getAddress()
Returns the raw IP address of this InetAddress object.

static InetAddress[] getAllByName(String host)
Given the name of a host, returns an array of its IP addresses, based on the
configured name service on the system.

static InetAddress

getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address .

static InetAddress

getByAddress(String host, byte[] addr)
Create an InetAddress based on the provided host name and IP address No
name service is checked for the validity of the address.

static InetAddress

getByName(String host)
Determines the IP address of a host, given the host's name.

String

getCanonicalHostName()
Gets the fully qualified domain name for this IP address.

String

getHostAddress()
Returns the IP address string in textual presentation.

String

getHostName()
Gets the host name for this IP address.


static InetAddress

getLocalHost()
Returns the local host.

/>
-4-


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

int

hashCode()
Returns a hashcode for this IP address.

boolean

isAnyLocalAddress()
Utility routine to check if the InetAddress in a wildcard address.

boolean

isLinkLocalAddress()
Utility routine to check if the InetAddress is an link local address.

boolean


isLoopbackAddress()
Utility routine to check if the InetAddress is a loopback address.

boolean

isMCGlobal()
Utility routine to check if the multicast address has global scope.

boolean

isMCLinkLocal()
Utility routine to check if the multicast address has link scope.

boolean

isMCNodeLocal()
Utility routine to check if the multicast address has node scope.

boolean

isMCOrgLocal()
Utility routine to check if the multicast address has organization scope.

boolean

isMCSiteLocal()
Utility routine to check if the multicast address has site scope.

boolean


isMulticastAddress()
Utility routine to check if the InetAddress is an IP multicast address.

boolean

isSiteLocalAddress()
Utility routine to check if the InetAddress is a site local address.

String

toString()
Converts this IP address to a String.

Chương II - Lập Trình Socket
Chú ý: Lập trình Socket truyền dữ liệu sẽ liên quan đến hai giao thức ở tầng
Transport (trong mô hình tham chiếu 7 tầng OSI), đó là giao thức truyền tin cậy
TCP và truyền không tin cậy UDP.

I, Socket :
- Lớp Socket dùng tạo kết nối từ máy khách đến máy chủ thường được khởi dựng
bằng các phương thức sau:
public Socket(String host, int port) throws UnknownHostException, IOException
Hàm này tạo một socket TCP với host và cổng xác định, và thực hiện liên kết với host
ở xa.
public Socket(InetAddress host, int port) throws IOException
/>
-5-



Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

Tương tự như constructor trước, constructor này tạo một socket TCP với thông tin là
địa chỉ của một host được xác định bởi một đối tượng InetAddress và số hiệu cổng
port, sau đó nó thực hiện kết nối tới host. Nó đưa ra ngoại lệ IOException nhưng
không đưa ra ngoại lệ UnknownHostException. Constructor đưa ra ngoại lệ trong
trường hợp không kết nối được tới host.
public Socket (String host, int port, InetAddress interface, int localPort) throws
IOException, UnknownHostException
Constructor này tạo ra một socket với thông tin là địa chỉ IP được biểu diễn bởi một
đối tượng String và một số hiệu cổng và thực hiện kết nối tới host đó. Socket kết nối
tới host ở xa thông qua một giao tiếp mạng và số hiệu cổng cục bộ được xác định bởi
hai tham số sau. Nếu localPort bằng 0 thì Java sẽ lựa chọn một cổng ngẫu nhiên có sẵn
nằm trong khoảng từ 1024 đến 65535.
public Socket (InetAddress host, int port, InetAddress interface, int localPort)
throws IOException, UnknownHostException
Constructor chỉ khác constructor trên ở chỗ địa chỉ của host lúc này được biểu diễn
bởi một đối tượng InetAddress.
- Một số phương thức hỗ trợ cho lớp Socket :
InputStream getInputStream() throws IOException : lấy về luồng nhập để máy
khách có thể đọc dữ liệu trả về từ máy chủ.
OutputStream getOutputStream() throws IOException: lấy về luồng xuất để máy
khách có thể ghi dữ liệu gửi đến máy chủ.
InetAddress getInetAddress(): lấy địa chỉ kết nối socket của máy chủ
int getPort(): lấy về số cổng dùng kết nối của máy chủ.
Hàm public void close() throws IOException: dùng để cắt đứt mọi kết nối.
- Ví Dụ : Máy khách kết nối đến cổng 2812 máy chủ (máy cục bộ) :
import java.net.*;

class MayKhach
{
public static void main(String[] args) throws Exception
{
System.out.println("Client khoi dong va ket noi Server");
Socket server = new Socket("localhost",2812);
System.out.println("Ket noi thanh cong may chu.");
server.close();
}
}

/>
-6-


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

Phụ Lục Tiếng Anh : Class Socket
Constructor Summary
Socket()
Creates an unconnected socket, with the system-default type of SocketImpl.
Socket(InetAddress address, int port)
Creates a stream socket and connects it to the specified port number at the
specified IP address.
Socket(InetAddress host, int port, boolean stream)
Deprecated. Use DatagramSocket instead for UDP transport.
Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
Creates a socket and connects it to the specified remote address on the specified

remote port.
protected

Socket(SocketImpl impl)
Creates an unconnected Socket with a user-specified SocketImpl.
Socket(String host, int port)
Creates a stream socket and connects it to the specified port number on the
named host.
Socket(String host, int port, boolean stream)
Deprecated. Use DatagramSocket instead for UDP transport.
Socket(String host, int port, InetAddress localAddr, int localPort)
Creates a socket and connects it to the specified remote host on the specified
remote port.

Method Summary
void

bind(SocketAddress bindpoint)
Binds the socket to a local address.

void

close()
Closes this socket.

void

connect(SocketAddress endpoint)
Connects this socket to the server.


void

connect(SocketAddress endpoint, int timeout)
Connects this socket to the server with a specified timeout value.

SocketChannel getChannel()
Returns the unique SocketChannel object associated with this socket, if any.
InetAddress

getInetAddress()
Returns the address to which the socket is connected.

InputStream

getInputStream()
Returns an input stream for this socket.

boolean

getKeepAlive()
Tests if SO_KEEPALIVE is enabled.

/>
-7-


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221


InetAddress

getLocalAddress()
Gets the local address to which the socket is bound.

int

getLocalPort()
Returns the local port to which this socket is bound.

SocketAddress getLocalSocketAddress()
Returns the address of the endpoint this socket is bound to, or null if it is not
bound yet.
boolean

getOOBInline()
Tests if OOBINLINE is enabled.

OutputStream getOutputStream()
Returns an output stream for this socket.
int

getPort()
Returns the remote port to which this socket is connected.

int

getReceiveBufferSize()
Gets the value of the SO_RCVBUF option for this Socket, that is the buffer
size used by the platform for input on this Socket.


SocketAddress getRemoteSocketAddress()
Returns the address of the endpoint this socket is connected to, or null if it is
unconnected.
boolean

getReuseAddress()
Tests if SO_REUSEADDR is enabled.

int

getSendBufferSize()
Get value of the SO_SNDBUF option for this Socket, that is the buffer size
used by the platform for output on this Socket.

int

getSoLinger()
Returns setting for SO_LINGER.

int

getSoTimeout()
Returns setting for SO_TIMEOUT.

boolean

getTcpNoDelay()
Tests if TCP_NODELAY is enabled.


int

getTrafficClass()
Gets traffic class or type-of-service in the IP header for packets sent from this
Socket

boolean

isBound()
Returns the binding state of the socket.

boolean

isClosed()
Returns the closed state of the socket.

boolean

isConnected()
Returns the connection state of the socket.

boolean

isInputShutdown()

/>
-8-


Tài Liệu Học Tập Lập Trình Mạng


Biên soạn : GV Bùi Tiến Trường – 0989995221

Returns wether the read-half of the socket connection is closed.
boolean

isOutputShutdown()
Returns wether the write-half of the socket connection is closed.

void

sendUrgentData(int data)
Send one byte of urgent data on the socket.

void

setKeepAlive(boolean on)
Enable/disable SO_KEEPALIVE.

void

setOOBInline(boolean on)
Enable/disable OOBINLINE (receipt of TCP urgent data) By default, this
option is disabled and TCP urgent data received on a socket is silently discarded.

void

setReceiveBufferSize(int size)
Sets the SO_RCVBUF option to the specified value for this Socket.


void

setReuseAddress(boolean on)
Enable/disable the SO_REUSEADDR socket option.

void

setSendBufferSize(int size)
Sets the SO_SNDBUF option to the specified value for this Socket.

static void

setSocketImplFactory(SocketImplFactory fac)
Sets the client socket implementation factory for the application.

void

setSoLinger(boolean on, int linger)
Enable/disable SO_LINGER with the specified linger time in seconds.

void

setSoTimeout(int timeout)
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.

void

setTcpNoDelay(boolean on)
Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).


void

setTrafficClass(int tc)
Sets traffic class or type-of-service octet in the IP header for packets sent from
this Socket.

void

shutdownInput()
Places the input stream for this socket at "end of stream".

void

shutdownOutput()
Disables the output stream for this socket.

String

toString()
Converts this socket to a String.

II, ServerSocket :
- Lớp ServerSocket được tạo trên máy chủ, dùng để tạo kết nối từ phía máy chủ đến
các máy khách. Một số hàm của lớp ServerSocket :

/>
-9-


Tài Liệu Học Tập Lập Trình Mạng


Biên soạn : GV Bùi Tiến Trường – 0989995221

Hàm dựng ServerSocket(int port) throws IOException : port là số hiệu cổng mà
ServerSocket phải lắng nghe để biết những kết nối từ phía máy khách gởi đến.
Hàm Socket accept() throws IOException : phương thức này thật sự dừng lại chờ
đợi cho đến khi nhận được thông tin kết nối và sẽ trả về đối tượng Socket của máy
khách nơi có yêu cầu nối vào máy chủ.
Hàm public void close() throws IOException : dùng để máy chủ cắt đứt mọi kết nối
đến các client.
- VD : Viết Máy chủ chờ đợi kết nối tại cổng 2812 :
import java.net.*;
class MayChu
{
public static void main(String[] args) throws Exception
{
System.out.println("Server khoi dong tai cong 2812");
ServerSocket server = new ServerSocket(2812);
Socket client = server.accept();
System.out.println("Ket noi may khach thanh cong.");
client.close();
server.close();
}
}
Phụ Lục Tiếng Anh : Class ServerSocket
Constructor Summary
ServerSocket()
Creates an unbound server socket.
ServerSocket(int port)
Creates a server socket, bound to the specified port.

ServerSocket(int port, int backlog)
Creates a server socket and binds it to the specified local port number, with the specified
backlog.
ServerSocket(int port, int backlog, InetAddress bindAddr)
Create a server with the specified port, listen backlog, and local IP address to bind to.
Method Summary
Socket

accept()
Listens for a connection to be made to this socket and accepts it.

void

bind(SocketAddress endpoint)

/>
- 10 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

Binds the ServerSocket to a specific address (IP address and port
number).
void

bind(SocketAddress endpoint, int backlog)
Binds the ServerSocket to a specific address (IP address and port
number).


void

close()
Closes this socket.

ServerSocketChannel getChannel()
Returns the unique ServerSocketChannel object associated with this
socket, if any.
InetAddress

getInetAddress()
Returns the local address of this server socket.

int

getLocalPort()
Returns the port on which this socket is listening.

SocketAddress

getLocalSocketAddress()
Returns the address of the endpoint this socket is bound to, or null if it
is not bound yet.

int

getReceiveBufferSize()
Gets the value of the SO_RCVBUF option for this ServerSocket, that
is the proposed buffer size that will be used for Sockets accepted from this

ServerSocket.

boolean

getReuseAddress()
Tests if SO_REUSEADDR is enabled.

int

getSoTimeout()
Retrive setting for SO_TIMEOUT.

protected void

implAccept(Socket s)
Subclasses of ServerSocket use this method to override accept() to
return their own subclass of socket.

boolean

isBound()
Returns the binding state of the ServerSocket.

boolean

isClosed()
Returns the closed state of the ServerSocket.

void


setReceiveBufferSize(int size)
Sets a default proposed value for the SO_RCVBUF option for sockets
accepted from this ServerSocket.

void

setReuseAddress(boolean on)
Enable/disable the SO_REUSEADDR socket option.

static void

setSocketFactory(SocketImplFactory fac)
Sets the server socket implementation factory for the application.

void

setSoTimeout(int timeout)
Enable/disable SO_TIMEOUT with the specified timeout, in

/>
- 11 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

milliseconds.
String


toString()
Returns the implementation address and implementation port of this
socket as a String.

III, Lớp DatagramSocket :
Lớp này dùng để chuyển một gói dữ liệu (biểu diễn bằng đối tượng DatagramPackage)
theo giao thức UDP. Dữ liệu được gửi đi không bảo đảm được nhận đầy đủ và có thể
bị lỗi trên đường truyền. Một số phương thức của DatagramSocket :
public DatagramSocket() throws SocketException: khởi dựng để tạo kết nối UDP
public DatagramSocket(int port) throws SocketException : khởi dựng để tạo kết
nối UDP với số hiệu port
public void synchronized receive(DatagramPackage p) throws IOException: nhận
gói dữ liệu về
public void synchronized send(DatagramPackage p) throws IOException: gửi gói
dữ liệu đi
public void synchronized close(): đóng kết nối

Phụ Lục Tiếng Anh : Class DatagramSocket
Constructor Summary
DatagramSocket()
Constructs a datagram socket and binds it to any available port on the local host machine.
protected

DatagramSocket(DatagramSocketImpl impl)
Creates an unbound datagram socket with the specified DatagramSocketImpl.

DatagramSocket(int port)
Constructs a datagram socket and binds it to the specified port on the local host machine.
DatagramSocket(int port, InetAddress laddr)
Creates a datagram socket, bound to the specified local address.

DatagramSocket(SocketAddress bindaddr)
Creates a datagram socket, bound to the specified local socket address.
/>
- 12 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

Method Summary
void

bind(SocketAddress addr)
Binds this DatagramSocket to a specific address & port.

void

close()
Closes this datagram socket.

void

connect(InetAddress address, int port)
Connects the socket to a remote address for this socket.

void

connect(SocketAddress addr)
Connects this socket to a remote socket address (IP address + port

number).

void

disconnect()
Disconnects the socket.

boolean

getBroadcast()
Tests if SO_BROADCAST is enabled.

DatagramChannel getChannel()
Returns the unique DatagramChannel object associated with this datagram
socket, if any.
InetAddress

getInetAddress()
Returns the address to which this socket is connected.

InetAddress

getLocalAddress()
Gets the local address to which the socket is bound.

int

getLocalPort()
Returns the port number on the local host to which this socket is bound.


SocketAddress

getLocalSocketAddress()
Returns the address of the endpoint this socket is bound to, or null if it is
not bound yet.

int

getPort()
Returns the port for this socket.

int

getReceiveBufferSize()
Get value of the SO_RCVBUF option for this DatagramSocket, that is the
buffer size used by the platform for input on this DatagramSocket.

SocketAddress

getRemoteSocketAddress()
Returns the address of the endpoint this socket is connected to, or null if it
is unconnected.

boolean

getReuseAddress()
Tests if SO_REUSEADDR is enabled.

int


getSendBufferSize()
Get value of the SO_SNDBUF option for this DatagramSocket, that is the
buffer size used by the platform for output on this DatagramSocket.

int

getSoTimeout()

/>
- 13 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

Retrive setting for SO_TIMEOUT.
int

getTrafficClass()
Gets traffic class or type-of-service in the IP datagram header for packets
sent from this DatagramSocket.

boolean

isBound()
Returns the binding state of the socket.

boolean


isClosed()
Returns wether the socket is closed or not.

boolean

isConnected()
Returns the connection state of the socket.

void

receive(DatagramPacket p)
Receives a datagram packet from this socket.

void

send(DatagramPacket p)
Sends a datagram packet from this socket.

void

setBroadcast(boolean on)
Enable/disable SO_BROADCAST.

static void

setDatagramSocketImplFactory(DatagramSocketImplFactory fac)
Sets the datagram socket implementation factory for the application.

void


setReceiveBufferSize(int size)
Sets the SO_RCVBUF option to the specified value for this
DatagramSocket.

void

setReuseAddress(boolean on)
Enable/disable the SO_REUSEADDR socket option.

void

setSendBufferSize(int size)
Sets the SO_SNDBUF option to the specified value for this
DatagramSocket.

void

setSoTimeout(int timeout)
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.

void

setTrafficClass(int tc)
Sets traffic class or type-of-service octet in the IP datagram header for
datagrams sent from this DatagramSocket.

IV, Lớp DatagramPackage :
- Lớp này dùng chứa một gói chứa dữ liệu gửi đi trên mạng theo kết nối
DatagramSocket. Một gói có thể chứa các thông tin như dữ liệu, chiều dài gói, các địa
chỉ IP và số cổng mà từ đó gói dữ liệu được gửi đi. Một số phương thức của lớp này

là:
public DatagramPackage(byte data[ ], int len): tạo ra gói dữ liệu chứa trong biến
data có chiều dài là len.
/>
- 14 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

public DatagramPackage(byte data[ ], int len, InetAddress iaddr, int port): tương
tự phương thức trên nhưng có thêm địa chỉ máy đích và số hiệu port.
public InetAddress getAddress(): trả về địa chỉ chứa trong gói dữ liệu.
public byte[ ] getData(): trả về dữ liệu thực sự chứa trong gói.
public getLength(): trả về chiều dài gói dữ liệu.
public getPort(): trả về số hiệu port chứa trong gói dữ liệu
Phụ Lục Tiếng Anh : Class DatagramPacket
Constructor Summary
DatagramPacket(byte[] buf, int length)
Constructs a DatagramPacket for receiving packets of length length.
DatagramPacket(byte[] buf, int length, InetAddress address, int port)
Constructs a datagram packet for sending packets of length length to the specified port number
on the specified host.
DatagramPacket(byte[] buf, int offset, int length)
Constructs a DatagramPacket for receiving packets of length length, specifying an offset into
the buffer.
DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)
Constructs a datagram packet for sending packets of length length with offset ioffsetto the
specified port number on the specified host.

DatagramPacket(byte[] buf, int offset, int length, SocketAddress address)
Constructs a datagram packet for sending packets of length length with offset ioffsetto the
specified port number on the specified host.
DatagramPacket(byte[] buf, int length, SocketAddress address)
Constructs a datagram packet for sending packets of length length to the specified port number
on the specified host.
Method Summary
InetAddress

getAddress()
Returns the IP address of the machine to which this datagram is being sent
or from which the datagram was received.

byte[]

getData()
Returns the data buffer.

int

getLength()
Returns the length of the data to be sent or the length of the data received.

int

getOffset()
Returns the offset of the data to be sent or the offset of the data received.

int


getPort()

/>
- 15 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

Returns the port number on the remote host to which this datagram is being
sent or from which the datagram was received.
SocketAddress

getSocketAddress()
Gets the SocketAddress (usually IP address + port number) of the remote
host that this packet is being sent to or is coming from.

void

setAddress(InetAddress iaddr)
Sets the IP address of the machine to which this datagram is being sent.

void

setData(byte[] buf)
Set the data buffer for this packet.

void


setData(byte[] buf, int offset, int length)
Set the data buffer for this packet.

void

setLength(int length)
Set the length for this packet.

void

setPort(int iport)
Sets the port number on the remote host to which this datagram is being
sent.

void

setSocketAddress(SocketAddress address)
Sets the SocketAddress (usually IP address + port number) of the remote
host to which this datagram is being sent.

Chương III – Kết Nối SOCKET Sử Dụng TCP
I, Mô Hình Hoạt Động :

II, Trình Tự Hoạt Động Của Máy Chủ (SERVER) :
/>
- 16 -


Tài Liệu Học Tập Lập Trình Mạng


Biên soạn : GV Bùi Tiến Trường – 0989995221

1, Khai Báo Thư Viện :
//thư viện khai báo việc nhập/xuất dữ liệu
import java.io.*;
//thư viện làm việc trên mạng
import java.net.*;
2, Kết nối máy chủ - máy khách :
//Biến server thuộc kiểu ServerSocket, nó thiết lập cổng chờ đợi của Server :
ServerSocket server = new ServerSocket(1234);
//Biến client thuộc kiểu Socket, nó cho phép máy khách được kết nối đến máy chủ :
Socket client = server.accept();
3, Khai Báo Các Biến Sử Dụng :
//Biến br dùng để đọc luồng dữ liệu được gửi đến từ máy khách
BufferedReader br = new BufferedReader(new
InputStreamReader(client.getInputStream()));
//Biến pw dùng để gửi thông tin từ máy chủ về máy khách
PrintWriter pw = new PrintWriter(client.getOutputStream());
//Biến st thuộc kiểu chuỗi, dùng để làm biến trung gian lưu dữ liệu
String st;
4, Máy chủ đọc dữ liệu được gửi đến từ máy khách thông qua biến br :
st = br.readLine();
Dữ liệu gửi đến sẽ là kiểu chuỗi, do đó nếu muốn chuyển sang KDL khác ta sử dụng
parse. Ví dụ muốn chuyển sang kiểu double, ta có :
double a = Double.parseDouble(st);
5, Xử lý dữ liệu được gửi đến, việc này ta nên viết thành 1 hàm xử lý bên ngoài hàm
main().Ví dụ muốn chuyển chuỗi thành chữ HOA, ta có :
String kq = CHUHOA(st);
Hàm xử lý được viết bên ngoài hàm main() :
public static String CHUHOA(String st)

{
return st.toUpperCase();
}
6, Gửi trả kết quả về máy khách thông qua biến pw :
pw.write(kq + "\n");
pw.flush();
7, Kết thúc phiên làm việc của máy chủ :
br.close();
pw.close();
client.close();
/>
- 17 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

server.close();

III, Trình Tự Hoạt Động Của Máy Khách (CLIENT) :
1, Khai Báo Thư Viện :
//thư viện khai báo việc nhập/xuất dữ liệu
import java.io.*;
//thư viện làm việc trên mạng
import java.net.*;
2, Kết nối máy chủ - máy khách :
//Biến server thuộc kiểu Socket, nó yêu cầu kết nối đến cổng xác định của máy chủ :
Socket server = new Socket("tên máy chủ",1234);
Tên máy chủ có thể là : tên máy cục bộ (localhost), tên máy chủ bất kỳ (H.ROOTSERVERS.NET), hoặc địa chỉ IP (128.63.2.53)

3, Khai Báo Các Biến Sử Dụng :
//Biến in dùng để đọc luồng dữ liệu được nhập từ bàn phím
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
///Biến br dùng để đọc luồng dữ liệu được gửi về từ máy chủ
BufferedReader br = new BufferedReader(new
InputStreamReader(server.getInputStream()));
//Biến pw dùng để gửi thông tin từ máy khách đến máy chủ
PrintWriter pw = new PrintWriter(server.getOutputStream());
//Biến st thuộc kiểu chuỗi, dùng để làm biến trung gian lưu dữ liệu
String st;
4, Máy khách nhập dữ liệu cần xử lý vào từ bàn phím :
System.out.print("Nhap du lieu : ");
st = in.readLine();
Kiểu dữ liệu nên đặt cố định là kiểu chuỗi, vì khi gửi đi tới máy chủ thì bắt buộc phải
là kiểu chuỗi.
5, Gửi dữ liệu từ máy khách đến máy chủ thông qua biến pw :
pw.write(st + "\n");
pw.flush();
6, Đọc dữ liệu được trả về từ máy chủ thông qua biến br :
String kq = br.readLine();
Sau khi đọc, tuỳ dữ liệu trả về là kiểu gì, bạn sử dụng parse để chuyển đổi theo yêu
cầu.Ví dụ muốn chuyển sang kiểu số nguyên :
String kq = br.readLine();
int a = Integer.parseInt(kq);
hoặc :
/>
- 18 -



Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

int a = Integer.parseInt(br.readLine());
7, In kết quả thu được lên màn hình :
System.out.println(“Ket qua tu may chu : " + kq);
8, Kết thúc phiên làm việc của máy khách :
br.close();
pw.close();
server.close();

Chương IV – Kết Nối SOCKET Sử Dụng UDP
I, Lập Trình UDP :
- Việc cài đặt ứng dụng UDP trong Java cần có hai lớp là DatagramPacket và
DatagramSocket.
DatagramPacket đóng gói các byte dữ liệu vào các gói tin UDP được gọi là datagram
và cho phép ta mở các datagram khi nhận được.
Một DatagramSocket đồng thời thực hiện cả hai nhiệm vụ nhận và gửi gói tin. Để
gửi dữ liệu, ta đặt dữ liệu trong một DatagramPacket và gửi gói tin bằng cách sử dụng
DatagramSocket. Để nhận dữ liệu, ta nhận một đối tượng DatagramPacket từ
DatagramSocket và sau đó đọc nội dung của gói tin.
- UDP không có bất kỳ khái niệm nào về liên kết giữa hai host. Một socket gửi tất cả
dữ liệu tới một cổng hoặc nhận tất cả dữ liệu từ một cổng mà không cần quan tâm host
nào gửi.
- Một DatagramSocket có thể gửi dữ liệu tới nhiều host độc lập hoặc nhận dữ liệu từ
nhiều host độc lập. DatagramSocket không dành riêng cho một liên kết cụ thể thể nào
cả như trong giao thức TCP.
- Các socket TCP xem liên kết mạng như là một luồng : ta gửi và nhận dữ liệu với các
luồng nhập và luồng xuất nhận được từ socket. UDP không cho phép điều này mà ta

phải làm việc với từng gói tin. Tất cả dữ liệu được đặt trong datagram được gửi đi
dưới dạng một gói tin.
- Gói tin này cũng có thể nhận được bởi một nhóm hoặc cũng có thể bị mất. Một gói
tin không nhất thiết phải liên quan đến gói tin tiếp theo. Cho trước hai gói tin, không
có cách nào để biết được gói tin nào được gửi trước và gói tin nào được gửi sau.

II, Gửi - Nhận Gói Tin UDP :
1, Nhận Gói Tin UDP :
Trước khi một ứng dụng có thể đọc các gói tin UDP được gửi bởi các máy ở xa, nó
phải gán một socket với một cổng UDP bằng cách sử dụng DatagramSocket, và tạo ra
một DatagramPacket sẽ đóng vai trò như là một bộ chứa cho dữ liệu của gói tin UDP.

/>
- 19 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

- Cú Pháp Lệnh Nhận Gói Tin Dữ Liệu :
//Khai Báo
int portSVR=2812;
DatagramSocket socket = new DatagramSocket(portSVR);
DatagramPacket packet;
byte [ ]data;
//Nhận Gói Tin
data = new byte[1024];
packet = new DatagramPacket(data,data.length);
socket.receive(packet);

String st = new String(packet.getData(),0,packet.getLength());

2, Gửi Gói Tin UDP :
- Lớp DatagramSocket cũng được sử dụng để gửi các gói tin. Khi gửi gói tin, ứng
dụng phải tạo ra một DatagramPacket, thiết lập địa chỉ và thông tin cổng, và ghi dữ
liệu cần truyền vào mảng byte.
- Nếu muốn gửi thông tin phúc đáp thì ta cũng đã biết địa chỉ và số hiệu cổng của gói
tin nhận được. Mỗi khi gói tin sẵn sàng để gửi, ta sử dụng phương thức send() của lớp
DatagramSocket để gửi gói tin đi.

/>
- 20 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

- Cú Pháp Lệnh Nhận Gói Tin Dữ Liệu :
//Khai Báo
int portSVR=2812;
DatagramSocket socket = new DatagramSocket(portSVR);
DatagramPacket packet;
byte [ ]data;
//đọc thông tin CLIENT từ gói tin nhận được
InetAddress ipCLT = packet.getAddress();
int portCLT = packet.getPort();
//Gửi Gói Tin
data = st.getBytes();
packet = new DatagramPacket(data,data.length,ipCLT,portCLT);

socket.send(packet);

III, Trình Tự Hoạt Động Máy Chủ UDP :
1, Khai báo cổng kết nối và các biến làm việc :
int portSVR=2812;
DatagramSocket socket = new DatagramSocket(portSVR);
DatagramPacket packet;
byte [ ]data;
2, Nhận gói tin được gửi đến từ máy khách :
data = new byte[1024];
packet = new DatagramPacket(data,data.length);
socket.receive(packet);
String st = new String(packet.getData(),0,packet.getLength());
Dữ liệu nhận về là gói tin được chuyển sang kiểu chuỗi. Nếu muốn đưa sang kiểu DL
khác, ta sử dụng parse như sau :
double a = Double.parseDouble(st);
3, Đọc trong gói tin packet, để lấy ra IP và Port của máy khách.Thông tin này giúp
máy chủ có thể biết gói tin được gửi đến từ máy nào và dùng nó để trả kết quả về máy
khách đó :
InetAddress ipCLT = packet.getAddress();
int portCLT = packet.getPort();
/>
- 21 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

4, Viết hàm xử lý dữ liệu nhận được từ gói tin, hàm này tốt nhất được viết bên ngoài

hàm main() :
String kq = CHUHOA(st);
Hàm xử lý được viết bên ngoài hàm main() :
public static String CHUHOA(String st)
{
return st.toUpperCase();
}
5, Gửi trả kết quả xử lý về cho máy khách :
data = kq.getBytes();
packet = new DatagramPacket(data,data.length,ipCLT,portCLT);
socket.send(packet);
6, Kết thúc phiên làm việc của máy chủ :
socket.close();

IV, Trình Tự Hoạt Động Máy Khách UDP :
1, Khai báo các biến làm việc :
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet;
byte [ ]data;
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
String st;
2, Máy khách nhập dữ liệu cần xử lý vào từ bàn phím :
System.out.print("Nhap du lieu : ");
st = in.readLine();
3, Gửi dữ liệu đến máy chủ theo IP và cổng kết nối :
int portSVR = 2812;
InetAddress ipSVR = InetAddress.getByName("tên máy chủ");
data = st.getBytes();
packet = new DatagramPacket(data,data.length,ipSVR,portSVR);

socket.send(packet);
4, Nhận kết quả trả về từ máy chủ :
data = new byte[1024];
packet = new DatagramPacket(data,data.length);
socket.receive(packet);
String kq = new String(packet.getData(),0,packet.getLength());
5, In kết quả nhận được lên màn hình :
System.out.println(“KQ nhan duoc tu may chu la : " + kq);
/>
- 22 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

6, Kết thúc phiên làm việc của máy Khách :
socket.close();

PHẦN BÀI TẬP THAM KHẢO
Bài 1 : Kết Nối TCP Sử Dụng Socket, chuẩn gửi nhận SỐ - SỐ
Trang Máy Chủ :
import java.io.*;
import java.net.*;
class TCPSS
{
public static void main(String[] args) throws Exception
{
int port = 2812;
ServerSocket server = new ServerSocket(port);

Socket client = server.accept();
BufferedReader br = new BufferedReader(new
InputStreamReader(client.getInputStream()));
PrintWriter pw = new PrintWriter(client.getOutputStream());
String st = br.readLine();
double so = Double.parseDouble(st);
double kqD = XuLy(so);
String kqS = String.valueOf(kqD);
pw.write(kqS + "\n");
pw.flush();
pw.close();
br.close();
client.close();
server.close();
}
public static double XuLy(double so)
{
return Math.pow(so,3);
}
}
Trang Máy Khách :
import java.io.*;
import java.net.*;
class TCPCS
/>
- 23 -


Tài Liệu Học Tập Lập Trình Mạng


Biên soạn : GV Bùi Tiến Trường – 0989995221

{
public static void main(String[] args) throws Exception
{
int portS = 2812;
InetAddress ipS = InetAddress.getByName("localhost");
Socket server = new Socket(ipS,portS);
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader br = new BufferedReader(new
InputStreamReader(server.getInputStream()));
PrintWriter pw = new PrintWriter(server.getOutputStream());
System.out.print("Nhap so bat ky : ");
double so = Double.parseDouble(in.readLine());
String st = String.valueOf(so);
pw.write(st+"\n");
pw.flush();
String kqS = br.readLine();
double kqD = Double.parseDouble(kqS);
System.out.println("Lap Phuong So = " + kqD);
pw.close();
br.close();
server.close();
}
}
Bài 2 : Kết Nối TCP Sử Dụng Socket, gửi nhận CHUỖI – CHUỖI
Trang Máy Chủ :
import java.io.*;
import java.net.*;

class TCPSC
{
public static void main(String[] args) throws Exception
{
int port = 2812;
ServerSocket server = new ServerSocket(port);
Socket client = server.accept();
BufferedReader br = new BufferedReader(new
InputStreamReader(client.getInputStream()));
PrintWriter pw = new PrintWriter(client.getOutputStream());
String st = br.readLine();
String kq = XuLy(st);
/>
- 24 -


Tài Liệu Học Tập Lập Trình Mạng

Biên soạn : GV Bùi Tiến Trường – 0989995221

pw.write(kq + "\n");
pw.flush();
pw.close();
br.close();
client.close();
server.close();
}
public static String XuLy(String st)
{
return st.toUpperCase();

}
}
Trang Máy Khách :
import java.io.*;
import java.net.*;
class TCPCC
{
public static void main(String[] args) throws Exception
{
int portS = 2812;
InetAddress ipS = InetAddress.getByName("localhost");
Socket server = new Socket(ipS,portS);
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader br = new BufferedReader(new
InputStreamReader(server.getInputStream()));
PrintWriter pw = new PrintWriter(server.getOutputStream());
System.out.print("Nhap chuoi bat ky : ");
String st = in.readLine();
pw.write(st+"\n");
pw.flush();
String kq = br.readLine();
System.out.println("Chuoi Hoa : " + kq);
pw.close();
br.close();
server.close();
}
}
Bài 3 : Kết Nối UDP Sử Dụng Socket, chuẩn gửi nhận SỐ - SỐ


/>
- 25 -


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×