Trang 164
Chng 8: LP TRÌNH SOCKET
I. Các kin thc liên quan
Trc khi bt u hc bài này các bn cn c li các kin thc liên quan sau:
- Giao thc, yêu cu ti thiu các bn phi nm c 3 giao thc : IP, TPC, UDP
- Cách ánh a ch IP, a ch dng tên min, giao thc chuyn i a ch IP thành a ch
tên min, và ngc li
- Mt sa chc bit: a ch lp, a ch broadcash, multicash…
- Cng giao thc
- Phân bit c s khác nhau, ging nhau gia 2 giao thc TCP và UDP
1. Gii thiu Socket
Socket là mt giao din lp trình ng (API - Application Program Interface) dng
ng, thông qua giao din này ta có th lp trình u khin vic truyn thông gia 2 máy
dng các giao thc mc thp nh TCP, UDP…, Socket là mt s tru tng hoá mc
cao, có th tng tng, nó nh là mt thit b truyn thông 2 chiu tng t nh tp tin,
chúng ta gi/ nhn d liu gia 2 máy, tng t nh vic c/ ghi trên tp tin.
liên lc thông qua Socket, ta cn tin hành các thao tác:
- To lp hay m mt Socket
+ Gn mt Socket vi mt a ch, a ch này chính là a ch ca máy mà nó cn liên lc
+ Thc hin vic liên lc, có 2 kiu liên lc tu thuc vào ch kt ni:
a) Liên lc trong ch không kt ni:
Hai tin trình liên lc vi nhau không kt ni trc tip
i thông p gi i phi kèm theo a ch ca ngi nhn
Hình thc liên lc này có c m:
ngi gi không chc chn thông p ca h có n tay ngi nhn không
t thông p có th gi nhiu ln
thông p gi sau có thn ích trc thông p gi trc ó
b) Liên lc trong ch kt ni:
Có mt ng kt ni “o” c thành lp gia 2 tin trình, trc khi mt kt ni c
thành lp thì mt trong 2 tin trình phi i tin trình kia yêu cu kt ni, có th s dng
Socket liên lc theo mô hình Client/Server. Trong mô hình này server s dng li gi
listen và accept lng nghe và chp nhn mt yêu cu kt ni
2. Lp trình Socket trong java
Java cung cp mt s lp cho phép các ng dng mng có th trao i vi nhau qua
ch Socket, c th lp Socket cung cp cho ta c ch liên lc trong ch kt ni (s
ng giao thc TCP) và lp DatagramSocket cho phép các ng dng mng liên lc vi
nhau trong ch không kt ni (s dng giao thc UDP), tt c các lp liên quan n vic
p trình Socket c java nhóm li và trong gói java.net
II. Kho sát mt s lp trong gói java.net
1. Lp InetAddress
i mt máy khi tham gia truyn thông cn phi có mt nh danh, nh danh này
phi là duy nht, nh danh này c th hin bng a ch IP hoc a ch di dng
Trang 165
tên min. Lp InetAddress biu th cho mt a ch ca mt máy nào ó, khi ta mun
liên lc vi mt máy xa, ta phi bit c a ch IP ca máy xa, tuy nhiên a
ch IP thì rt khó nh, ôi khi ta không th bit chính xác a ch IP ca máy ó, bi
vì nhiu nguyên nhân khác nhau nh: máy ó khi ng t xa hoc c ni vào
nhà cung cp dch v Internet, do vy mi ln kt ni vào nhà cung cp dch v ISP
ta li có 1 a ch IP khác nhau. Vy th thì làm th nào ta có th liên lc vi máy
xa khi ta ch bit a ch máy ó di dng tên min?, câu tr li là lp
InetAddress ã làm u ó cho ta, lp này tng chuyn a ch dng tên min
thành a ch IP và ngc li.
p InetAddress cung cp mt s phng thc tnh (static) dùng chuyn i da ch
i dng tên min thành a ch IP và ngc li. Có mt s phng thc sau mà bn cn
quan tâm:
Phng pháp Mô t
Public void equals( Object obj) So sánh 2 i tng
Public byte[] getAddress() y va ch IP di dng mng byte
public static InetAddress[]
getAllByName(String host)
throws UnknownHostException
Tr v mng i tng InetAddress, vì mt máy
có th có nhiu a ch IP (do có nhiu card
ng), nên phng thc này tr v mt mng
cha tt c các a ch tng ng vi tên min.
public static InetAddress
getByName(String host)
throws UnknownHostException
Tr li i tng InetAddress có tên c ch
ra, tên này là mt xâu kí t di dng tên min
hoc a ch IP
public String getHostAddress() Tr va ch IP ca máy ch
public String getHostName() Tr v tên ca máy ch
public static InetAddress
getLocalHost()
throws UnknownHostException
Tr vi tng InetAddress kt hp vi chính
máy ó
public boolean isMulticastAddress() Kim tra xem a ch này có phi là a ch
Multicast không
Chú ý:
Trong gói java.net còn lp Inet4Address và lp Inet6Address hai lp này th hin cho
các a ch IP version 4 và IP version 6, nó gm tt c các thành phn ca lp
InetAddress
Ta cn thêm mnh import p java.net.InetAddress trc khi có th s dng nó.
Trang 166
Phng thc getByName s có gng phân gii tên min thành a ch IP tng ng bng
cách: Trc tiên nó i tìm trong cache, nu không tìm thy nó tìm tip trong tp host,
u vn không tìm thy nó s c gng kt ni n máy ch DNS yêu cu phân gii
tên này thành a ch IP, nu không th phân gii c tên này thì nó s sinh ra mt
ngoi l UnknownHostException, th nên bn cn t chúng vào mt khi try ..catch.
Ví d 1: Minh ho cách s dng các phng thc getByName to ra mt 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 chy chng trình nh sau:
www.theht.edu.vn/127.0.0.1Ngoài cách truyn vào phng thc getByName mt xâu ký t
th hin tên máy bn ta th truyn vào mt xâu th hin a ch IP ca máy nh sau:
InetAddress address = InetAddress.getByName("192.168.101.1");
Ví d 2: To ra mt InetAddress tng ng vi máy cc 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 chy chng trình nh sau:
Trang 167
theht1/192.168.101.1Ví d 3: Nu máy bn có cài nhiu card mng bn có th ly v mt
ng các InetAddess tng ng vi a ch IP cho tng card mng ó:
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 chy chng 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 kt qu nh trên là do máy ca tôi
có cài 4 card mng, tng ng vi mi card mng tôi t mt da ch IP cho nó.
u máy ca bn có ni mng Internet bn có th kim tra xem máy ch
www.microsoft.com ca Microsoft c cài bao nhiêu b giao tip mng bng cách
thayInetAddress.getAllByName("www.theht.edu.vn"); bi
InetAddress.getAllByName("www.microsoft.com");
Ví d 4: y v tên máy khi bit a ch IP ca nó, ly v tên ca máy ta s dng
phng thc 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: Ly v ch IP ca máy khi bit tên ca máy, ly va ch IP ca máy ta s
ng phng thc 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 ly va ch IP tng ng vi mt tên min bt k
không nht thit là máy cc b nh trên, chng hn bn có th ly v ch IP ca máy
www.theht.edu.vn hoc 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: Kim tra xem hai a ch tên min có cùng mt a ch IP hay không. kim tra
u này ta s dng phn thc 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 dng chng trìn HostLookup tng t nh chng trình NSLookup ca
Windows, chng trình này có nhim v khi bn gõ vào a ch IP thì nó s tr va ch
tên min và ngc 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 kim tra xem a ch host di dng tên min 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. Lp URL và URI
Lp URL là mt lp rt n gin giúp bn trong vic nh v và ly v d liu t
ng, mà bn không cn phi quan tâm n giao thc c s dng, nh dng ca d liu
hoc không cn quan tâm n cách giao tip vi máy ch.
o ra mt URL
Không ging nhi tng InetAddress bn có th s dng hàm to ca lp URL to ra
t i tng URL mi. Có sáu hàm to khác nhau ca lp URL cho phép bn to ra các
URL vi các yêu cu khác nhau. Tt c các hàm to này u ném ra ngoi l
MalformedURLException nu bn to ra mt URL t mt giao thc không c h tr
hoc các thông tin cung cp trong URL không chính xác thì bn s nhn c mt ngoi l
MalformedURLException
a) To ra mt URL t mt xâu
public URL(String url) throws MalformedURLException
Ging nh các hàm to khác bn ch cn dùng toán t new và cng ging các hàm to khác
a lp nó ném ra ngoi l MalformedURLException.
Ví d 1: To ra mt URL t mt xâu và bt ngoi l sinh ra
try {
URL u = new URL(" />}
catch (MalformedURLException ex) {
System.err.println(ex);
}
Ví d 2: Ví d này to ra mt s URL và kim tra xem giao thc tng ng vi các URL
có c h tr trong virtual machine ca bn 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 chy trên máy ca tôi nh sau:
http is supported
https is supported
ftp is supported
mailto is supported
b) To ra mt URL t các phn riêng l
Hàm to này cho gm ba phn riêng bit, chúng cho bit: Giao thc, tên máy ch,
p tin mà URL này s dng.
public URL(String protocol, String hostname, String file)
throws MalformedURLException
Hàm to này s tng t port là giá tr mc nh, tu theo giao thc mà bn ch
nh nó s s dng mà giá tr mc 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 chng trình trên to ra mt URL chn />ng mc nh là 80
Trang 173
to ra mt URL vi mt cng chnh bn s dng hàm to sau:
public URL(String protocol, String host, int port, String file) throws
MalformedURLException
Ví d: To ra mt URL gán vi máy localhost trên cng 8080
try {
URL u = new URL("http", "localhost", 8080, "/index.html");
}
catch (MalformedURLException ex) {
System.err.println(ex);
}
Ví d này to ra mt URL trn http://localhost: 8080/index.html
c) To ra mt URL t mt URL khác
Hàm to này cho phép bn to ra mt URL t mt 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 trn còn u2 thì
ang trn mailinglists.html.
t vài phng thc ca lp URL
- public String getHost( ) tr v tên ca máy ch
- public int getPort( ) tr v cng c s dng
- public int getDefaultPort( ) tr v cng mc nh ca giao thc c s dng. Ví d nh :
http=80, email=25, ftp=23...
- public String getFile( ) tr v tên tp tin
- public String getPath( ) // Java 1.3 tr vng dn n file, ng dn này thng 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 mt 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 phng thc 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 chy chng 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) Nhn v d
liu t URL
n có th nhn v d liu c chnh trong URL bng cách s dng cách phn thc
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
Phng thc này s kt ni n máy ch và yêu cu ly v mt InputStream gn vi tài
nguyên c chnh trong URL.
Trang 175
Ví d sau ly v ni dung ca trang web c chnh 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 chy 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 bn</font></p></body></html>
- Phng thc public URLConnection openConnection( ) throws IOException
Phng thc này m mt socket kt ni n máy ch. Nu phng thc này tht bi
nó ném ra ngoi 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 mt phng thc c np chng nh sau:
public URLConnection openConnection(Proxy proxy) throws IOException
Phng thc này rt hu dng khi trong mng ca bn có s dng proxy
- Phng thc 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 chy nh sau:
I got a sun.net.www.protocol.http.HttpURLConnection$HttpInputStreamNu thay URL
u = new URL("http://localhost:80/index.html"); bi URL u = new
URL("http://localhost:80/print.gif"); kt qu thu c nh sau:
I got a sun.awt.image.URLImageSource
3. Lp Socket
Lp này c dùng cho c máy ch và máy khách. i vi máy khách nó thng dùng
t ni n máy ch, còn i vi máy ch nó thng dùng áp li kt ni t máy khách.
Thông thng ta to ra mt Socket bng cách s dng hàm to ca lp Socket. Sau ây là
t s hàm to ca lp Socket.
3.1 Mt s hàm to ca lp Socket
a) public Socket(String host, int port) throws UnknownHostException, IOException
Ta thng s dng hàm to này kt ni n máy ch. Trong hàm to này tên ca
máy là mt xâu ký t, tên ca máy ch có th là tên mìên hoc a ch IP. Nu nh không
n ti máy này thì nó s ném ra mt ngoi l UnknownHostException. Nu Socket không
th m vì bt c lý do nào thì nó ném ra ngoi l IOException.
Trang 177
Ví d: Kt ni 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 thng s dng hàm to này kt ni n máy ch khi bit mt InetAddress gn vi
nó.
Ví d sau kt cng kt ni n máy ch www.theht.edu.vn trên cng 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
Nu máy ca bn có nhiu b giao tip mng thì khi kt ni n máy ch ta cn ch
ra kt ni c thit lp thông qua giao din mng nào.
u tham s port nhn giá tr 0 thi java runtime s chn ngu nhiên mt cng nào ó cha
c s dng trong khong 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 to này cng tng t nh hàm to 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. Ly v thông tin gn vi Socket
- Phng thc public InetAddress getInetAddress( ) dùng ly vi tng InetAddress
ng ng vi 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);
}
- Phng thc public int getPort( ) dùng ly v cng ca 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
- Phng thc public int getLocalPort( ) dùng ly v cng ca máy cc b dùng
giao tip vi 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);
}
- Phng thc public InetAddress getLocalAddress( ) dùng ly vi tng
InetAddress gán vi card mng dùng giao tip.
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 mt s thông tin gn vi 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");
}