Tải bản đầy đủ (.ppt) (33 trang)

Lập tình socket với Java

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 (216.42 KB, 33 trang )


Network Programming
1
Lập trình Socket với Java
Network Programmin
g
2
Nội dung bài học

Lớp InetAddress

Truyền tin với giao thức TCP

TCP Sockets

Ví dụ về máy chủ/khách TCP

Truyền tin với giao thức UDP

Datagram Sockets

Ví dụ về máy chủ/khách UDP
Network Programmin
g
3
Các classes trong gói java.net

Gói java.net chứa các classes cho phép thực hiện lập trình
mạng

ContentHandler



DatagramPacket

DatagramSocket

InetAddress

MulticastSocket

ServerSocket

Socket

SocketImpl

URL

URLConnection

URLEncoder

URLStreamHandler
Network Programmin
g
4
Exceptions in Java

BindException

ConnectException


MalformedURLException

NoRouteToHostException

ProtocolException

SocketException

UnknownHostException

UnknownServiceException
Network Programmin
g
5
Lớp InetAddress

Xử lý địa chỉ Internet theo tên và địa chỉ IP

Các hàm chuyển đổi tên/địa chỉ:
/* trả về một đối tượng kiểu InetAddress*/
public static InetAddress getByName(String host) throws
UnknownHostException
/* trả về chuỗi đối tượng kiểu InetAddress*/
public static InetAddress[] getAllByName(String host) throws
UnknownHostException
public static InetAddress getLocalHost() throws UnknownHostException
public boolean isMulticastAddress()
public String getHostName() /*trả về tên miền*/
public byte[] getAddress() /*trả về địa chỉ IP dạng chuỗi byte*/

public String getHostAddress() /*trả về địa chỉ IP dạng ký tự*/
public int hashCode()
public boolean equals(Object obj)
public String toString()
Network Programmin
g
6
import java.net.*;
import java.io.*;
public class IPFinder
{
public static void main(String[] args) throws IOException
{
String host;
BufferedReader input =
new BufferedReader(
new InputStreamReader(System.in));
System.out.print("\n\nEnter host name: ");
host = input.readLine(); /*Đọc chuỗi ký tự nhập từ bàn phím*/
try
{
InetAddress address = InetAddress.getByName(host);
System.out.println("IP address: " + address.toString());
}
catch (UnknownHostException e)
{
System.out.println("Could not find " + host);
}
}
}

Network Programmin
g
7
Lấy địa chỉ của máy chủ
import java.net.*;
public class MyLocalIPAddress
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getLocalHost();
System.out.println (address.toString());
}
catch (UnknownHostException e)
{
System.out.println("Could not find local address!");
}
}
}
Network Programmin
g
8
Truyền tin với giao thức TCP
TCP client
TCP server
socket()
ServerSocket ()
ServerSocket.
accept()

BufferedReader.
readLine()
PrintWriter.
println()
read()
connect()
write()
close()
Connection
request
EOF
Wait next
request
Process request
data (request)
data (reply)
BufferedReader.
readLine()
ServerSocket.
close()
Network Programmin
g
9
Lớp Java.net.Socket

Lớp cơ bảncủa Java để thực hiện truyền tin TCP phía
máy khách

Thiết lập hoặc ngắt kết nối và thiết lập các tùy chọn socket


Kết nối được thiết lập khi khởi tạo đối tượng

Mỗi đối tượng Socket được gán với một máy chủ duy nhất

Để kết nối với một máy chủ khác, phải tạo ra một đối tượng
Socket mới
public Socket(String host, int port) throws UnknownHostException,
IOException
public Socket(InetAddress address, int port) throws IOException
public Socket(String host, int port, InetAddress localAddress, int
localPort)
throws IOException
public Socket(InetAddress address, int port, InetAddress localAddress,
int localPort) throws IOException
Network Programmin
g
10
The Java.net.Socket Class (2)

Gửi và nhận dữ liệu được thực hiện thông qua dòng dữ liệu xuất/nhập

Có một số hàm để lấy đối tượng là dòng nhập cho một socket và dòng xuất cho
socket đó.
public InputStream getInputStream() throws IOException
public OutputStream getOutputStream() throws IOException

Lấy thông tin về một Socket

public InetAddress getInetAddress( )


public int getPort( )

public int getLocalPort( )

public InetAddress getLocalAddress( )

Đóng socket:

public void close() throws IOException

public void shutdownInput( ) throws IOException // Java 1.3

public void shutdownOutput( ) throws IOException // Java 1.3

public boolean isInputShutdown( ) // Java 1.4

public boolean isOutputShutdown( ) // Java 1.4
Network Programmin
g
11
TCP Sockets
MÁY KHÁCH:
1. Thiết lập kết nối đến máy chủ
Socket link =
new Socket(inetAddress.getLocalHost(),1234);
2. Thiết lập các dòng xuất/nhập dữ liệu
3. Gửi và nhận dữ liệu
4. Đóng kết nối
Network Programmin
g

12
Ví dụ: DaytimeClient.java
import java.net.*;
import java.io.*;
public class DaytimeClient {
public static void main(String[] args) {
String hostname;
int port;
if (args.length > 0) {
hostname = args[0];
port = Integer.parseInt(args[1]);
}
else {
hostname = "time.nist.gov";
port = 13;
}
Network Programmin
g
13
Example: DaytimeClient.java (2)
try {
Socket theSocket = new Socket(hostname, port);
InputStream timeStream = theSocket.getInputStream( );
StringBuffer time = new StringBuffer( );
int c;
while ((c = timeStream.read( )) != -1)
time.append((char) c);
String timeString = time.toString( ).trim( );
System.out.println("It is " + timeString + " at " + hostname);
} // end try

catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
} // end main
} // end DaytimeClient
Network Programmin
g
14
Lớp Java.net.ServerSocket

Lớp java.net.ServerSocket bao gồm

Các hàm khởi tạo đối tượng ServerSocket

Các hàm chờ kết nối

Các hàm thiết lập các loại tùy chọn socket máy chủ

Các hàm thường dùng khác như toString( )

Có bốn hàm khởi tạo ServerSocket cho phép thiết lập
cổng, kích thước hàng đợi của các yêu cầu kết nối và
network interface gán cho tiến trình máy chủ

public ServerSocket(int port) throws IOException

public ServerSocket(int port, int backlog) throws IOException


public ServerSocket(int port, int backlog, InetAddress bindAddr)
throws IOException

public ServerSocket( ) throws IOException // Java 1.4
Network Programmin
g
15
Lớp Java.net.ServerSocket - Chấp nhận
và đóng kết nối

public Socket accept() throws IOException

Dừng thực hiện của tiến trình và đợi kết nối từ
máy khách

Khi có một máy khách kết nối đến, hàm accept( )
sẽ trả về một đối tượng Socket

public void close() throws IOException

Đóng socket máy chủ và giải phóng cổng chờ
Network Programmin
g
16
TCP Sockets
MÁY CHỦ:
1. Tạo một đối tượng ServerSocket
ServerSocket servSocket = new ServerSocket(1234);
2. Đưa máy chủ vào trạng thái chờ

Socket link = servSocket.accept();
3. Thiết lập các dòng xuất/nhập dữ liệu
4. Gửi và nhận dữ liệu
out.println(awaiting data…);
String input = in.readLine();
5. Đóng kết nối
link.close()
Network Programmin
g
17
Thiết lập dòng xuất/nhập dữ liệu

Khi một socket được kết nối

chúng ta có thể gửi dữ liệu thông qua một dòng xuất dữ liệu

chúng ta có thể nhận dữ liệu thông qua một dòng nhập dữ liệu

Sử dụng hàm getInputStream and getOutputStream of class
Socket để thiết lập dòng xuất/nhập dữ liệu
BufferedReader in =
new BufferedReader(
new InputStreamReader(link.getInputStream()));
PrintWriter out =
new PrintWriter(link.getOutputStream(),true);
Network Programmin
g
18
Ví dụ về máy chủ TCP Echo
import java.net.*; // need this for InetAddress, Socket, ServerSocket

import java.io.*; // need this for I/O stuff
public class TCPEchoServer {
static final int BUFSIZE=1024; // define a constant used as size of buffer
static public void main(String args[]) {
if (args.length != 1) {
throw new IllegalArgumentException("Must specify a port!");
}
int port = Integer.parseInt(args[0]);
try {
ServerSocket ss = new ServerSocket(port); // Create Server Socket (passive socket)
while (true) {
Socket s = ss.accept();
handleClient(s);
}
} catch (IOException e) {
System.out.println("Fatal I/O Error !");
System.exit(0);
}
}
Network Programmin
g
19
Ví dụ về máy chủ TCP Echo(2)
static void handleClient(Socket s) throws IOException {
byte[] buff = new byte[BUFSIZE];
int bytesread = 0;
// print out client's address
System.out.println("Connection from " + s.getInetAddress().getHostAddress());
// Set up streams
InputStream in = s.getInputStream();

OutputStream out = s.getOutputStream();
// read/write loop
while ((bytesread = in.read(buff)) != -1) {
out.write(buff,0,bytesread);
}
s.close();
}
}
Network Programmin
g
20
Lớp java.net.DatagramPacket

Biểu diễn các gói dữ liệu UDP

Cung cấp các hàm

Lấy và thiết lập địa chỉ đích/nguồn từ/vào tiêu đề IP

Lấy và thiết lập cổng giao tiếp đích/nguồn

Nhận và thiết lập gói dữ liệu UDP
Network Programmin
g
21
Hàm khởi tạo DatagramPacket
Với bên nhận:
DatagramPacket(byte[] buf, int len);
Với bên gửi:
DatagramPacket( byte[] buf, int len

InetAddress a, int port);
Network Programmin
g
22
Các hàm DatagramPacket
byte[] getData();
void setData(byte[] buf);
void setAddress(InetAddress a);
void setPort(int port);
InetAddress getAddress();
int getPort();
Địa chỉ đích
Có thể là địa
chỉ/cổng nguồn/đích
Network Programmin
g
23
Lớp DatagramSocket

Tạo datagram socket để nhận
DatagramPacket.

Không có phân biệt giữa socket máy khách và socket
máy chủ

Một DatagramSocket có thể gửi cho nhiều địa chỉ
đích khác nhau.

Địa chỉ đích được lưu tại DatagramPacket


public DatagramSocket() throws SocketException
public DatagramSocket(int port) throws
SocketException
public DatagramSocket(int port, InetAddress laddr)
throws SocketException
Network Programmin
g
24
Gửi và nhận gói dữ liệu UDP

public void send(DatagramPacket dp) throws IOException

Gửi gói dữ liệu UDP với đối tượng kiểu DatagramPacket được
tạo ra

public void receive(DatagramPacket dp) throws IOException

Nhận gói dữ liệu UDP và lưu lại tại đối tượng kiểu
DatagramPacket được tạo ra từ trước

public void close( )

Giải phóng cổng đang đựoc sử dụng bới socket đó

public int getLocalPort( )

Trả về số hiệu cổng mà socket đang sử dụng

public InetAddress getLocalAddress( )


Trả về địa chỉ IP mà socket đang sử dụng
Network Programmin
g
25
Điều khiển kết nối – với Java 1.2

public void connect(InetAddress host, int port)

Gửi và nhận gói tin từ một điạ chỉ IP và cổng được định trước

Không giống như kết nối TCP

public void disconnect( )

public int getPort( )

public InetAddress getInetAddress( )

public InetAddress getRemoteSocketAddress( ) // Java 1.4

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

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