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

Lạp trình Socket

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 (2.88 MB, 41 trang )

Trang 164
Chng 8: LP TRÌNH SOCKET
I. Các kin thc liên quan
Trc khi bt u hc bài này các bn cn c li các kin thc liên quan sau:
- Giao thc, yêu cu ti thiu các bn phi nm c 3 giao thc : IP, TPC, UDP
- Cách ánh a ch IP, a ch dng tên min, giao thc chuyn i a ch IP thành a ch
tên min, và ngc li
- Mt sa chc bit: a ch lp, a ch broadcash, multicash…
- Cng giao thc
- Phân bit c s khác nhau, ging nhau gia 2 giao thc TCP và UDP
1. Gii thiu Socket
Socket là mt giao din lp trình ng (API - Application Program Interface) dng
ng, thông qua giao din này ta có th lp trình u khin vic truyn thông gia 2 máy
 dng các giao thc mc thp nh TCP, UDP…, Socket là mt s tru tng hoá  mc
cao, có th tng tng, nó nh là mt thit b truyn thông 2 chiu tng t nh tp tin,
chúng ta gi/ nhn d liu gia 2 máy, tng t nh vic c/ ghi trên tp tin.
 liên lc thông qua Socket, ta cn tin hành các thao tác:
- To lp hay m mt Socket
+ Gn mt Socket vi mt a ch, a ch này chính là a ch ca máy mà nó cn liên lc
+ Thc hin vic liên lc, có 2 kiu liên lc tu thuc vào ch kt ni:
a) Liên lc trong ch không kt ni:
Hai tin trình liên lc vi nhau không kt ni trc tip
i thông p gi i phi kèm theo a ch ca ngi nhn
Hình thc liên lc này có c m:
ngi gi không chc chn thông p ca h có n tay ngi nhn không
t thông p có th gi nhiu ln
thông p gi sau có thn ích trc thông p gi trc ó
b) Liên lc trong ch kt ni:
Có mt ng kt ni “o” c thành lp gia 2 tin trình, trc khi mt kt ni c
thành lp thì mt trong 2 tin trình phi i tin trình kia yêu cu kt ni, có th s dng
Socket  liên lc theo mô hình Client/Server. Trong mô hình này server s dng li gi


listen và accept lng nghe và chp nhn mt yêu cu kt ni
2. Lp trình Socket trong java
Java cung cp mt s lp cho phép các ng dng mng có th trao i vi nhau qua
 ch Socket, c th lp Socket cung cp cho ta c ch liên lc trong ch kt ni (s
ng giao thc TCP) và lp DatagramSocket cho phép các ng dng mng liên lc vi
nhau trong ch không kt ni (s dng giao thc UDP), tt c các lp liên quan n vic
p trình Socket c java nhóm li và  trong gói java.net
II. Kho sát mt s lp trong gói java.net
1. Lp InetAddress
i mt máy khi tham gia truyn thông cn phi có mt nh danh, nh danh này
phi là duy nht, nh danh này c th hin bng a ch IP hoc a ch di dng
Trang 165
tên min. Lp InetAddress biu th cho mt a ch ca mt máy nào ó, khi ta mun
liên lc vi mt máy  xa, ta phi bit c a ch IP ca máy  xa, tuy nhiên a
ch IP thì rt khó nh, ôi khi ta không th bit chính xác a ch IP ca máy ó, bi
vì nhiu nguyên nhân khác nhau nh: máy ó khi ng t xa hoc c ni vào
nhà cung cp dch v Internet, do vy mi ln kt ni vào nhà cung cp dch v ISP
ta li có 1 a ch IP khác nhau. Vy th thì làm th nào  ta có th liên lc vi máy
 xa khi ta ch bit a ch máy ó di dng tên min?, câu tr li là lp
InetAddress ã làm u ó cho ta, lp này tng chuyn a ch dng tên min
thành a ch IP và ngc li.
p InetAddress cung cp mt s phng thc tnh (static) dùng  chuyn i da ch
i dng tên min thành a ch IP và ngc li. Có mt s phng thc sau mà bn cn
quan tâm:
Phng pháp Mô t
Public void equals( Object obj) So sánh 2 i tng
Public byte[] getAddress() y va ch IP di dng mng byte
public static InetAddress[]
getAllByName(String host)
throws UnknownHostException

Tr v mng i tng InetAddress, vì mt máy
có th có nhiu a ch IP (do có nhiu card
ng), nên phng thc này tr v mt mng
cha tt c các a ch tng ng vi tên min.
public static InetAddress
getByName(String host)
throws UnknownHostException
Tr li i tng InetAddress có tên c ch
ra, tên này là mt xâu kí t di dng tên min
hoc a ch IP
public String getHostAddress() Tr va ch IP ca máy ch
public String getHostName() Tr v tên ca máy ch
public static InetAddress
getLocalHost()
throws UnknownHostException
Tr vi tng InetAddress kt hp vi chính
máy ó
public boolean isMulticastAddress() Kim tra xem a ch này có phi là a ch
Multicast không
Chú ý:
Trong gói java.net còn lp Inet4Address và lp Inet6Address hai lp này th hin cho
các a ch IP version 4 và IP version 6, nó gm tt c các thành phn ca lp
InetAddress
Ta cn thêm mnh  import p java.net.InetAddress trc khi có th s dng nó.
Trang 166
Phng thc getByName s có gng phân gii tên min thành a ch IP tng ng bng
cách: Trc tiên nó i tìm trong cache, nu không tìm thy nó tìm tip trong tp host,
u vn không tìm thy nó s c gng kt ni n máy ch DNS  yêu cu phân gii
tên này thành a ch IP, nu không th phân gii c tên này thì nó s sinh ra mt
ngoi l UnknownHostException, th nên bn cn t chúng vào mt khi try ..catch.

Ví d 1: Minh ho cách s dng các phng thc getByName  to ra mt InetAddress
import java.net.*;
class InetAddress1 {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.theht.edu.vn");
System.out.println(address);
}
catch (UnknownHostException ex) {
System.out.println("Could not find www.theht.edu.vn");
}
}
}
t qu chy chng trình nh sau:
www.theht.edu.vn/127.0.0.1Ngoài cách truyn vào phng thc getByName mt xâu ký t
th hin tên máy bn ta th truyn vào mt xâu th hin a ch IP ca máy nh sau:
InetAddress address = InetAddress.getByName("192.168.101.1");
Ví d 2: To ra mt InetAddress tng ng vi máy cc b:
import java.net.*;
class MyAddress {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
}
catch (UnknownHostException ex) {
System.out.println("Could not find this computer's address.");
}
}
}

t qu chy chng trình nh sau:
Trang 167
theht1/192.168.101.1Ví d 3: Nu máy bn có cài nhiu card mng bn có th ly v mt
ng các InetAddess tng ng vi a ch IP cho tng card mng ó:
import java.net.*;
class AllAddressesOfTheht {
public static void main(String[] args) {
try {
InetAddress[] addresses =
InetAddress.getAllByName("www.theht.edu.vn");
for (int i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]);
}
}
catch (UnknownHostException ex) {
System.out.println("Could not find www.theht.edu.vn");
}
}
}
t qu chy chng trình nh sau:
www.theht.edu.vn /192.168.101.1www.theht.edu.vn /10.0.0.2www.theht.edu.vn
/162.163.10.5www.theht.edu.vn /3.152.90.25s d cho kt qu nh trên là do máy ca tôi
có cài 4 card mng, tng ng vi mi card mng tôi t mt da ch IP cho nó.
u máy ca bn có ni mng Internet bn có th kim tra xem máy ch
www.microsoft.com ca Microsoft c cài bao nhiêu b giao tip mng bng cách
thayInetAddress.getAllByName("www.theht.edu.vn"); bi
InetAddress.getAllByName("www.microsoft.com");
Ví d 4: y v tên máy khi bit a ch IP ca nó,  ly v tên ca máy ta s dng
phng thc getHostName nh sau:
import java.net.*;

class ReverseTest {
public static void main(String[] args) {
try {
InetAddress ia = InetAddress.getByName("162.163.10.5");
System.out.println(ia.getHostName());
} catch (Exception ex) {
System.err.println(ex);
}
}
}
Trang 168
t qu ra nh sau:
theht
Ví d 5: Ly v ch IP ca máy khi bit tên ca máy,  ly va ch IP ca máy ta s
ng phng thc getHostAddress nh sau:
import java.net.*;
class GetHostAddress {
public static void main(String[] args) {
try {
InetAddress me = InetAddress.getLocalHost();
String dottedQuad = me.getHostAddress();
System.out.println("My address is " + dottedQuad);
}
catch (UnknownHostException ex) {
System.out.println("I'm sorry. I don't know my own address.");
}
}
}
t qu in ra nh sau:
My address is 192.168.101.1Ta có th ly va ch IP tng ng vi mt tên min bt k

không nht thit là máy cc b nh trên, chng hn bn có th ly v ch IP ca máy
www.theht.edu.vn hoc www.microsoft.com nh sau:
import java.net.*;
class GetHostAddress1 {
public static void main(String[] args) {
try {
InetAddress me = InetAddress.getByName("www.theht.edu.vn");
String dottedQuad = me.getHostAddress();
System.out.println("Address is " + dottedQuad);
}
catch (UnknownHostException ex) {
System.out.println("I'm sorry. I don't know my own address.");
}
}
}
t qu in ra nh sau:
Address is 192.168.101.1
Trang 169
Ví d 6: Kim tra xem hai a ch tên min có cùng mt a ch IP hay không.  kim tra
u này ta s dng phn thc equals nh sau:
import java.net.*;
class Equal {
public static void main(String args[]) {
try {
InetAddress add1 = InetAddress.getByName("www.theht.edu.vn");
InetAddress add2 = InetAddress.getByName("www.theht.com.vn");
if (add1.equals(add2)) {
System.out.println("Hai dia chi nay co cung IP");
}
else {

System.out.println("Hai dia chi nay khac IP");
}
}
catch (UnknownHostException ex) {
System.out.println("Khong the tim thay host.");
}
}
}
t qu cho nh sau:
Hai dia chi nay khac nhau
Ví d 7: Xây dng chng trìn HostLookup tng t nh chng trình NSLookup ca
Windows, chng trình này có nhim v khi bn gõ vào a ch IP thì nó s tr va ch
tên min và ngc lai:
import java.net.*;
import java.io.*;
public class HostLookup {
public static void main(String[] args) {
if (args.length > 0) {
// Su dung tham so dong lenh
for (int i = 0; i < args.length; i++) {
System.out.println(lookup(args[i]));
}
}
else {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Trang 170
System.out.println(
"Enter names and IP addresses.Enter \"exit\" or \"quit\" to quit.");
try {
while (true) {

String host = in.readLine();
if (host.equalsIgnoreCase("exit") ||
host.equalsIgnoreCase("quit")) {
break;
}
System.out.println(lookup(host));
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
private static String lookup(String host) {
InetAddress node;
try {
node = InetAddress.getByName(host);
}
catch (UnknownHostException ex) {
return "Cannot find host " + host;
}
if (isHostname(host)) {
//Dia chi nay duoi dang ten mien
return node.getHostAddress();
}
else {
// Dia chi nay duoi dang IP
return node.getHostName();
}
}

//Hàm kim tra xem a ch host di dng tên min hay a ch IP
private static boolean isHostname(String host) {
char[] ca = host.toCharArray();
for (int i = 0; i < ca.length; i++) {
Trang 171
if (!Character.isDigit(ca[i])) {
if (ca[i] != '.')return true;
}
}
return false;
}
}
2. Lp URL và URI
Lp URL là mt lp rt n gin giúp bn trong vic nh v và ly v d liu t
ng, mà bn không cn phi quan tâm n giao thc c s dng, nh dng ca d liu
hoc không cn quan tâm n cách giao tip vi máy ch.
o ra mt URL
Không ging nhi tng InetAddress bn có th s dng hàm to ca lp URL  to ra
t i tng URL mi. Có sáu hàm to khác nhau ca lp URL cho phép bn to ra các
URL vi các yêu cu khác nhau. Tt c các hàm to này u ném ra ngoi l
MalformedURLException nu bn to ra mt URL t mt giao thc không c h tr
hoc các thông tin cung cp trong URL không chính xác thì bn s nhn c mt ngoi l
MalformedURLException
a) To ra mt URL t mt xâu
public URL(String url) throws MalformedURLException
Ging nh các hàm to khác bn ch cn dùng toán t new và cng ging các hàm to khác
a lp nó ném ra ngoi l MalformedURLException.
Ví d 1: To ra mt URL t mt xâu và bt ngoi l sinh ra
try {
URL u = new URL(" />}

catch (MalformedURLException ex) {
System.err.println(ex);
}
Ví d 2: Ví d này to ra mt s URL và kim tra xem giao thc tng ng vi các URL
có c h tr trong virtual machine ca bn hay không
/* Which protocols does a virtual machine support? */
import java.net.*;
class ProtocolTester {
public static void main(String[] args) {
testProtocol(""); // hypertext transfer protocol
testProtocol(" // secure http
// file transfer protocol
testProtocol(" /> testProtocol("mailto:"); // Simple Mail Transfer Protocol
testProtocol("telnet://dibner.poly.edu/"); // telnet
testProtocol("file:///etc/passwd"); // local file access
testProtocol("gopher://gopher.anc.org.za/"); // gopher
testProtocol( // Lightweight Directory Access Protocol
Trang 172
"ldap://ldap.itd.umich.edu/o=University%20of%20Michigan,c=US?postalAddress");
testProtocol( // JAR
"jar: /> + "/com/macfaq/io/StreamCopier.class");
testProtocol("nfs://utopia.poly.edu/usr/tmp/"); // NFS, Network File System
testProtocol("jdbc:mysql://luna.metalab.unc.edu:3306/NEWS");
// a custom protocol for JDBC
// rmi, a custom protocol for remote method invocation
testProtocol("rmi://metalab.unc.edu/RenderEngine");
testProtocol("doc:/UsersGuide/release.html"); // custom protocols for HotJava
testProtocol("netdoc:/UsersGuide/release.html");
testProtocol("systemresource://www.adc.org/+/index.html");
testProtocol("verbatim: /> }

private static void testProtocol(String url) {
try {
URL u = new URL(url);
System.out.println(u.getProtocol() + " is supported");
}
catch (MalformedURLException ex) {
String protocol = url.substring(0, url.indexOf(':'));
System.out.println(protocol + " is not supported");
}
}
}
t qu chy trên máy ca tôi nh sau:
http is supported
https is supported
ftp is supported
mailto is supported
b) To ra mt URL t các phn riêng l
Hàm to này cho gm ba phn riêng bit, chúng cho bit: Giao thc, tên máy ch,
p tin mà URL này s dng.
public URL(String protocol, String hostname, String file)
throws MalformedURLException
Hàm to này s tng t port là giá tr mc nh, tu theo giao thc mà bn ch
nh nó s s dng mà giá tr mc nh này là khác nhau: Ví d nh : http thì port=80,
ftp=23...
Ví d:
try {
URL u = new URL("http", "www.microsoft.com", "/index.html");
}
catch (MalformedURLException ex) {
// All VMs should recognize http

}
n chng trình trên to ra mt URL chn />ng mc nh là 80
Trang 173
  to ra mt URL vi mt cng chnh bn s dng hàm to sau:
public URL(String protocol, String host, int port, String file) throws
MalformedURLException
Ví d: To ra mt URL gán vi máy localhost trên cng 8080
try {
URL u = new URL("http", "localhost", 8080, "/index.html");
}
catch (MalformedURLException ex) {
System.err.println(ex);
}
Ví d này to ra mt URL trn http://localhost: 8080/index.html
c) To ra mt URL t mt URL khác
Hàm to này cho phép bn to ra mt URL t mt URL khác, cú pháp nh sau:
public URL(URL base, String relative) throws MalformedURLException
Ví d:
try {
URL u1 = new URL(" /> URL u2 = new URL (u1, "mailinglists.html");
}
catch (MalformedURLException ex) {
System.err.println(ex);
}
Trong ví d này thì u1 ang trn còn u2 thì
ang trn mailinglists.html.
t vài phng thc ca lp URL
- public String getHost( ) tr v tên ca máy ch
- public int getPort( ) tr v cng c s dng
- public int getDefaultPort( ) tr v cng mc nh ca giao thc c s dng. Ví d nh :

http=80, email=25, ftp=23...
- public String getFile( ) tr v tên tp tin
- public String getPath( ) // Java 1.3 tr vng dn n file, ng dn này thng là
t query string.
- public String getRef( ), trong ví d sau thì getRef s tr v xtocid1902914
URL u = new URL(
" />System.out.println("The fragment ID of " + u + " is " + u.getRef( ));
- public String getQuery( ) // Java 1.3 tr v mt query string trong URL
Ví d: Trong ví d này thì getQuery s tr v category=Piano
URL u = new URL(
" />System.out.println("The query string of " + u + " is " + u.getQuery( ));
- public String getUserInfo( ) // Java 1.3 tr v user name
- public String getAuthority( ) // Java 1.3
Trang 174
Ví d sau minh ho các phng thc trên
import java.net.*;
class URLSplitter {
public static void main(String args[]) {
try {
URL u = new URL("");
System.out.println("The URL is " + u);
System.out.println("The scheme is " + u.getProtocol());
System.out.println("The user info is " + u.getUserInfo());
String host = u.getHost();
if (host != null) {
int atSign = host.indexOf('@');
if (atSign != -1) host = host.substring(atSign + 1);
System.out.println("The host is " + host);
}
else {

System.out.println("The host is null.");
}
System.out.println("The port is " + u.getPort());
System.out.println("The path is " + u.getPath());
System.out.println("The ref is " + u.getRef());
System.out.println("The query string is " + u.getQuery());
} // end try
catch (MalformedURLException ex) {
System.err.println("is not a URL I understand.");
}
System.out.println();
} // end main
} // end URLSplitter
t qu chy chng trình nh sau:
The URL is The scheme is httpThe user info is nullThe host is
java.sun.comThe port is -1The path is The ref is nullThe query string is nullc) Nhn v d
liu t URL
n có th nhn v d liu c chnh trong URL bng cách s dng cách phn thc
sau:
public InputStream openStream( ) throws IOException
public URLConnection openConnection( ) throws IOException
public URLConnection openConnection(Proxy proxy) throws IOException // 1.5
public Object getContent( ) throws IOException
public Object getContent(Class[] classes) throws IOException // 1.3
public final InputStream openStream( ) throws IOException
Phng thc này s kt ni n máy ch và yêu cu ly v mt InputStream gn vi tài
nguyên c chnh trong URL.
Trang 175
Ví d sau ly v ni dung ca trang web c chnh và in ra màn hình
import java.net.*;

import java.io.*;
class SourceViewer {
public static void main(String[] args) {
try { //Open the URL for reading
URL u = new URL("http://localhost:80/index.html");
InputStream in = u.openStream(); // buffer the input to increase performance
in = new BufferedInputStream(in); // chain the InputStream to a Reader
Reader r = new InputStreamReader(in);
int c;
while ( (c = r.read()) != -1) {
System.out.print( (char) c);
}
}
catch (MalformedURLException ex) {
System.err.println(is not a parseable URL");
}
catch (IOException ex) {
System.err.println(ex);
}
} // end main
} // end SourceViewer
t qu chy nh sau:
<html><head><meta http-equiv="Content-Type"content="text/html; charset=iso-8859-
1"><title> Web Posting Information </title></head><body><p><font
face=".VnTime">Xin chào các bn</font></p></body></html>
- Phng thc public URLConnection openConnection( ) throws IOException
Phng thc này m mt socket kt ni n máy ch. Nu phng thc này tht bi
nó ném ra ngoi l IOException.
Ví d:
try {

URL u = new URL(" />try {
URLConnection uc = u.openConnection( );
InputStream in = uc.getInputStream( );
// read from the connection...
} // end try
catch (IOException ex) {
System.err.println(ex);
}
} // end try
catch (MalformedURLException ex) {
System.err.println(ex);
}
Trang 176
Trong java 1.5 còn mt phng thc c np chng nh sau:
public URLConnection openConnection(Proxy proxy) throws IOException
Phng thc này rt hu dng khi trong mng ca bn có s dng proxy
- Phng thc public final Object getContent( ) throws IOException
Ví d:
import java.net.*;
import java.io.*;
class ContentGetter {
public static void main(String[] args) {
//Open the URL for reading
try {
URL u = new URL("http://localhost:80/index.html");
try {
Object o = u.getContent();
System.out.println("I got a " + o.getClass().getName());
} // end try
catch (IOException ex) {

System.err.println(ex);
}
} // end try
catch (MalformedURLException ex) {
System.err.println("is not a parseable URL");
}
} // end main
} // end ContentGetter
t qu chy nh sau:
I got a sun.net.www.protocol.http.HttpURLConnection$HttpInputStreamNu thay URL
u = new URL("http://localhost:80/index.html"); bi URL u = new
URL("http://localhost:80/print.gif"); kt qu thu c nh sau:
I got a sun.awt.image.URLImageSource
3. Lp Socket
Lp này c dùng cho c máy ch và máy khách. i vi máy khách nó thng dùng 
t ni n máy ch, còn i vi máy ch nó thng dùng áp li kt ni t máy khách.
Thông thng ta to ra mt Socket bng cách s dng hàm to ca lp Socket. Sau ây là
t s hàm to ca lp Socket.
3.1 Mt s hàm to ca lp Socket
a) public Socket(String host, int port) throws UnknownHostException, IOException
Ta thng s dng hàm to này  kt ni n máy ch. Trong hàm to này tên ca
máy là mt xâu ký t, tên ca máy ch có th là tên mìên hoc a ch IP. Nu nh không
n ti máy này thì nó s ném ra mt ngoi l UnknownHostException. Nu Socket không
th m vì bt c lý do nào thì nó ném ra ngoi l IOException.
Trang 177
Ví d: Kt ni n web server www.theht.edu.vn
try {
Socket toTheht= new Socket("www.theht.edu.vn", 80);
//~ Socket toTheht= new Socket("162.163.10.5", 80);
// send and receive data...

}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
- public Socket(InetAddress host, int port) throws IOException
Ta thng s dng hàm to này  kt ni n máy ch khi bit mt InetAddress gn vi
nó.
Ví d sau kt cng kt ni n máy ch www.theht.edu.vn trên cng 80
try {
InetAddress theht = InetAddress.getByName("www.theht.edu.vn");
//~ InetAddress theht = InetAddress.getByName("162.135.10.5");
Socket thehtSocket = new Socket(theht , 80);
// send and receive data...
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
- public Socket(String host, int port, InetAddress interface, int localPort) throws
IOException, UnknownHostException
Nu máy ca bn có nhiu b giao tip mng thì khi kt ni n máy ch ta cn ch
ra kt ni c thit lp thông qua giao din mng nào.
u tham s port nhn giá tr 0 thi java runtime s chn ngu nhiên mt cng nào ó cha
c s dng trong khong 1024 à65535.
Ví d:

try {
InetAddress inward = InetAddress.getByName("theht");
Socket socket = new Socket("www.theht.edu.vn", 80, inward, 0);
// work with the sockets...
}
catch (UnknownHostException ex) { System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
Trang 178
- public Socket(InetAddress host, int port, InetAddress interface, int localPort) throws
IOException
Hàm to này cng tng t nh hàm to trên.
Ví d:
try {
InetAddress inward = InetAddress.getByName("theht");
InetAddress http= InetAddress.getByName("www.theht.edu.vn");
Socket socket = new Socket(http, 80, inward, 0);
// work with the sockets...
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
3.2. Ly v thông tin gn vi Socket
- Phng thc public InetAddress getInetAddress( ) dùng  ly vi tng InetAddress
ng ng vi máy remote.

try {
Socket theSocket = new Socket("java.sun.com", 80);
InetAddress host = theSocket.getInetAddress( );
System.out.println("Connected to remote host " + host);
} // end try
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
- Phng thc public int getPort( ) dùng  ly v cng ca máy remote.
Ví d:
try {
Socket theSocket = new Socket("java.sun.com", 80);
int port = theSocket.getPort( );
System.out.println("Connected on remote port " + port);
} // end try
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
Trang 179
- Phng thc public int getLocalPort( ) dùng  ly v cng ca máy cc b dùng 
giao tip vi máy  xa.
Ví d:
try {
Socket theSocket = new Socket("java.sun.com", 80);

int localPort = theSocket.getLocalPort( );
System.out.println("Connecting from local port " + localPort);
} // end try
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
- Phng thc public InetAddress getLocalAddress( ) dùng  ly vi tng
InetAddress gán vi card mng dùng  giao tip.
Ví d:
try {
Socket theSocket = new Socket(hostname, 80);
InetAddress localAddress = theSocket.getLocalAddress( );
System.out.println("Connecting from local address " + localAddress);
} // end try
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
Ví d sau in ra màn hình mt s thông tin gn vi Socket
import java.net.*;
import java.io.*;
public class SocketInfo {
public static void main(String[] args) {
try {
Socket theSocket = new Socket("www.theht.edu.vn", 80);

System.out.println("Connected to " + theSocket.getInetAddress()
+ " on port " + theSocket.getPort() + " from port "
+ theSocket.getLocalPort() + " of "
+ theSocket.getLocalAddress());
} // end try
catch (UnknownHostException ex) {
System.err.println("I can't find host");
}

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

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