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

lập trình mạng nguyễn cao đạt chương 4 lập trình mạng trong java sinhvienzone com

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

Si

nh
Vi
en

Zo

ne

.C

om

Chương 4: Lập trình mạng trong Java

SinhVienZone.com

/>

Chương 3

1. Socket trong java

om

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

.C

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

nh
Vi
en

-

Zo

ne

-

Server ở chế độ có kết nối
-

DatagramSocket: hỗ trợ các phương thức liên quan tới socket ở cả client

-

Si


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
SinhVienZone.com

/>

Chương 3

1. Socket trong java

om

Lớp InetAddress

.C

Class mô tả về địa chỉ IP (Internet Protocol)

ne


– 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

nh
Vi
en

Zo


hostname)


public static InetAddess InetAddress.getLocalHost()

– Để lấy địa chỉ IP hay tên dùng các phương thức:
getHostAddress()



getHostName()

Si




SinhVienZone.com

/>

Chương 3

1. Socket trong java

om

Lớp InetAddress

Si

nh
Vi
en

Zo

ne

.C

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");
}
}
}

SinhVienZone.com

/>

Chương 3

1. Socket trong java

om

Lớp InetAddress

Si

nh

Vi
en

Zo

ne

.C

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");
}
}
}

SinhVienZone.com

/>


Chương 3

1. Socket trong java

om

Lớp Socket

nh
Vi
en

Zo

ne

.C

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ộ.

Si






SinhVienZone.com

/>

Chương 3

1. Socket trong java

om

Lớp Socket

public OutputStream getOutputStream() throws IOException


ne



.C

- Sử dụng Streams



Zo

Trả về một output stream cho việc viết các byte đến socket này.
public InputStream getInputStream() throws IOException

Si

nh
Vi
en

Trả về một input stream cho việc đọc các byte từ socket này.

SinhVienZone.com

/>

Chương 3

1. Socket trong java


om

Lớp Socket, ví dụ kết nối tới một server

Si

nh
Vi
en

Zo

ne

.C

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

SinhVienZone.com

/>

Chương 3

1. Socket trong java

Si

nh
Vi
en

Zo

ne

.C

om


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

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

SinhVienZone.com

/>

Chương 3


1. Socket trong java

Si

nh
Vi
en

Zo

ne

.C

om

Lập trình Socket với UDP
9 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.
9 Không cần thiết lập kết nối giữa client và server.
9 Sender phải gởi kèm địa chỉ IP và port đích
9 Server khi nhận dữ liệu sẽ phân tích địa chỉ của sender để truyền lại.
9 Có thể server chấp nhận nhiều client tại một thời điểm.

SinhVienZone.com

/>

Chương 3


1. Socket trong java
Ví dụ lập trình Socket với UDP

Client

.C
ne

nh
Vi
en

create socket,
port=x, for
incoming request:
serverSocket =
DatagramSocket()

om

(running on hostid)

Zo

Server

read request from
serverSocket

Si


write reply to
serverSocket
specifying client
host address,
port umber

SinhVienZone.com

create socket,
clientSocket =
DatagramSocket()
Create, address (hostid, port=x,
send datagram request
using clientSocket

read reply from
clientSocket
close
clientSocket

/>

Chương 3

1. Socket trong java

.C

om


Ví dụ lập trình Socket với UDP
UDPClient.java
import java.io.*;
import java.net.*;

Zo

ne

class UDPClient {
public static void main(String args[]) throws Exception
{

nh
Vi
en

BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();

Si

InetAddress IPAddress = InetAddress.getByName("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
SinhVienZone.com


/>

Chương 3

1. Socket trong java

om

Ví dụ lập trình Socket với UDP
UDPClient.java

Zo

clientSocket.send(sendPacket);

ne

.C

DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
9876);

nh
Vi
en

DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);

Si

String modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
SinhVienZone.com

/>

Chương 3

1. Socket trong java

om

Ví dụ lập trình Socket với UDP
UDPServer.java

ne

.C

import java.io.*;
import java.net.*;

nh

Vi
en

Zo

class UDPServer {
public static void main(String args[]) throws Exception
{

Si

DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
SinhVienZone.com

/>

Chương 3

1. Socket trong java

om


Ví dụ lập trình Socket với UDP
UDPServer.java

ne

int port = receivePacket.getPort();

.C

InetAddress IPAddress = receivePacket.getAddress();

nh
Vi
en

Zo

String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);

}

Si

serverSocket.send(sendPacket);
}
}


SinhVienZone.com

/>

Chương 3

1. Socket trong java

Si

nh
Vi
en

Zo

ne

.C

om

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.

SinhVienZone.com

/>

Chương 3

1. Socket trong java
Ví dụ lập trình Socket với TCP

Client

(running on hostid)

om

Server

Zo

ne

.C

create socket,
port=x, for

incoming request:
welcomeSocket =
ServerSocket()

TCP

setup

nh
Vi
en

wait for incoming
connection request connection
connectionSocket =
welcomeSocket.accept()

send request using
clientSocket

Si

read request from
connectionSocket

create socket,
connect to hostid, port=x
clientSocket =
Socket()


write reply to
connectionSocket
close
connectionSocket

SinhVienZone.com

read reply from
clientSocket
close
clientSocket

/>

Chương 3

1. Socket trong java

.C

om

Ví dụ lập trình Socket với TCP
TCPClient.java
import java.io.*;
import java.net.*;

nh
Vi
en


Zo

ne

class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));

Si

Socket clientSocket = new Socket("hostname", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());

SinhVienZone.com

/>

Chương 3

1. Socket trong java

om

Ví dụ lập trình Socket với TCP

TCPClient.java

Zo

sentence = inFromUser.readLine();

ne

.C

BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));

nh
Vi
en

outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);

Si

clientSocket.close();
}
}

SinhVienZone.com

/>


Chương 3

1. Socket trong java

om

Ví dụ lập trình Socket với TCP
TCPServer.java

nh
Vi
en

Zo

ne

.C

import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;

ServerSocket welcomeSocket = new ServerSocket(6789);


Si

while(true) {

Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));

SinhVienZone.com

/>

Chương 3

1. Socket trong java

om

Ví dụ lập trình Socket với TCP
TCPServer.java

ne

.C

DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());

Zo


clientSentence = inFromClient.readLine();

nh
Vi
en

capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}

Si

}

SinhVienZone.com

/>

Chương 3

2. Ví dụ xây dựng ứng dụng WebServer

nh
Vi
en

Zo

ne


.C

om

Chỉ xử lý một yêu cầu http
Chập nhận và phân tích yêu cầu http
Lấy các file được yêu cầu từ hệ thống file trên server
Tạo thông điệp http trả lời
Gửi trả lời về phía client

Si

-

SinhVienZone.com

/>

Chương 3

2. Ví dụ xây dựng ứng dụng WebServer

Si

nh
Vi
en

Zo


ne

.C

om

Ví dụ client gửi tới server lệnh GET /hinh.jpeg HTTP/1.1\n\n
Server trả về client file hinh.jpeg và kích thước của file

SinhVienZone.com

/>

Chương 3

2. Ví dụ xây dựng ứng dụng WebServer đơn
giản

om

WebServer.java

nh
Vi
en

Zo

ne


.C

import java.io.*;
import java.net.*;
import java.util.*;
class WebServer{
public static void main(String argv[]) throws Exception {
String requestMessageLine;
String fileName;
ServerSocket listenSocket = new ServerSocket(6789);
Socket connectionSocket = listenSocket.accept();

Si

BufferedReader inFromClient =
new BufferedReader(new

InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
SinhVienZone.com

/>

Chương 3

2. Ví dụ xây dựng ứng dụng WebServer

om


WebServer.java

.C

requestMessageLine = inFromClient.readLine();

Zo

ne

StringTokenizer tokenizedLine =
new StringTokenizer(requestMessageLine);

nh
Vi
en

if (tokenizedLine.nextToken().equals("GET")){
fileName = tokenizedLine.nextToken();
if (fileName.startsWith("/") == true )
fileName = fileName.substring(1);

Si

File file = new File(fileName);
int numOfBytes = (int) file.length();
FileInputStream inFile = new FileInputStream (fileName);
byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);


SinhVienZone.com

/>

×