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

Tài liệu Lập trình mạng P4 doc

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

Chương 4: Lậptrìnhmạng trong Java
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ộtsố gói tiêu
biểu
- InetAddress: Quảnlýđịachỉ internet bao gồm địachỉ 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ếtnối
- ServerSocket: hỗ trợ phương thức liên quan tới socket cho chương trình
Server ở chếđộcó kếtnố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
- URL
- URLConnection
Chương 3
1. Socket trong java
Lớp InetAddress
Class mô tả vềđịachỉ IP (Internet Protocol)
–Cácphương thức getLocalHost, getByName, hay getAllByName để tạomột
InetAddress instance:
• public static InetAddess InetAddress.getByName(String hostname)
• public static InetAddess [] InetAddress.getAllByName(String
hostname)
• public static InetAddess InetAddress.getLocalHost()
– Để lấy địachỉ IP hay tên dùng các phương thức:
• getHostAddress()
• getHostName()
Chương 3
1. Socket trong java


Lớp InetAddress
Ví dụ: In địachỉ 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");
}
}
}
Chương 3
1. Socket trong java
Lớp InetAddress
Ví dụ: In địachỉ 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");
}
}
}
Chương 3
1. Socket trong java
Lớp Socket
Class mô tả về socket
–Tạomộ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ềđịachỉ mà socket kếtnối đến.
• int getPort() : trả về port mà socket kếtnối đến.
• InetAddress getLocalAddress() : trả vềđịachỉ cụcbộ.
• int getLocalPort() : trả về port cụcbộ.
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ệcviế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.
Chương 3
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 "
+ 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
Chương 3
Lớp ServerSocket
– Class mô tả về ServerSocket
–Tạomột ServerSocket
• ServerSocket(int port) throws IOException
• ServerSocket(int port, int backlog) throws IOException

• ServerSocket(int port, int backlog, InetAddress bindAddr)
throws
IOException
–Cácphương thức trong ServerSocket
• Socket accept() throws IOException : Lắng nghe mộtkếtnối đến
socket này và chấpnhậnnó.
• void close() throws IOException : Đóng socket.
• InetAddress getInetAddress() : trả vềđịachỉ cụcbộ của socket
• int getLocalPort() : Trả về port mà server đang lắng nghe.
• void setSoTimeout(int timeout) throws SocketException
1. Socket trong java
Chương 3
Lập trình Socket với UDP
9 Cung cấpcơ chế truyền không tin cậygiữa các nhóm các byte
(datagrams) giữa client và server.
9 Không cầnthiếtlậpkếtnốigiữa client và server.
9 Sender phảigởikèmđịachỉ IP và port đích
9 Server khi nhậndữ liệusẽ phân tích địachỉ của sender để truyềnlại.
9 Có thể server chấpnhậnnhiều client tạimộtthời điểm.
1. Socket trong java
Ví dụ lập trình Socket với UDP
Chương 3
1. Socket trong java

close
clientSocket
Server
(running on hostid)
read reply from
clientSocket

create socket,
clientSocket =
DatagramSocket()
Client
Create, address (hostid, port=x,
send datagram request
using clientSocket
create socket,
port=x, for
incoming request:
serverSocket =
DatagramSocket()
read request from
serverSocket
write reply to
serverSocket
specifying client
host address,
port umber
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));
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();
Chương 3
1. Socket trong java
Ví dụ lập trình Socket với UDP
UDPClient.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

×