Bài giảng Computer Networks 1 (Mạng máy tính 1) - Lecture 9: Socket Programming with Java - Phạm Trần Vũ
Lecture 9:
Socket Programming with Java
Using InetAddress (1)
ꢀ Get local address
import java.net.*;
public class HostInfo {
public static void main(String args[]) {
HostInfo host = new HostInfo();
host.init();
}
public void init() {
try {
Systemme());
} catch (UnknownHostException ex) {
System.err.println("Cannot find local host");
}
}
}
Using InetAddress (2)
ꢀ
In địa ch
ỉ
IP của proxy.hcmut.edu.vn
import java.net.*;
class kku{
public static void main (String args[]) {
try {
InetAd
InetAddress.getAllByName(“proxy.hcmut.edu.vn");
System.out.println(addresses[i]);
}
}
catch (Un
System.out.println("Could not find
proxy.hcmut.edu.vn");
}
}
}
Using Socket (1)
ꢀ
K
ế
t n
ố
i
đ
ên 1 số webserver
import java.net.*;
import java.io.*;
public class getSocketInfo {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
try {
System.out.println("Connected to " +
" f
theSocket.getLocalPort() + " of " +
theSocket.getLocalAddress());
Using Socket (2)
} 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 (
System.err.println(e);
}
} // end for
} // end main
} // end getSocketInfo
Using ServerSocket (1)
ꢀ
DateTime Server
import java.net.*;
import java.io.*;
import java.util.Date;
public class DayTimeServer {
public final static int daytimePort = 5000;
ServerSocket theServer;
Socket theConnection;
PrintStream p;
try {
theServer = new
ServerSocket(daytimePort);
Java Multi-Threading
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
class PrimeRun implements Runnable {
long minPrime;
PrimeRun ( long minPrime ) {
this.minPrime = minPrime;
}
public void run() {
. . .
}
}
11. PrimeRun p = new PrimeRun(143);
12. new Thread(p).start();
Stop a Thread (1)
ꢀ
ꢀ
Using Thread.interrupt(), after changing loop condition
This method does not work with ServerSocket.accept()!
public void stop() {
running = false;
this.inter
}
public void run() {
running = true;
while (running){
Socke
...
}
}
Tải về để xem bản đầy đủ
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Computer Networks 1 (Mạng máy tính 1) - Lecture 9: Socket Programming with Java - Phạm Trần Vũ", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
File đính kèm:
- bai_giang_computer_networks_1_mang_may_tinh_1_lecture_9_sock.pdf