bai 3 - lap trinh socket voi java

44
1 Network Programming Lập trình Socket với Java

Upload: pham-hong-phi

Post on 06-Nov-2015

33 views

Category:

Documents


5 download

DESCRIPTION

Socket With Java

TRANSCRIPT

Socket Programming in JavaNetwork Programming
TCP Sockets
Datagram Sockets
Network Programming
Các classes trong gói java.net
Gói java.net cha các classes cho phép thc hin lp trình mng
InetAddress:
Ánh x, chuyn i và trình din a ch IP
ServerSocket:
Socket
DatagramSocket:
MulticastSocket:
giao din socket gi và nhn các gói tin multicast
Network Programming
URL
Biu din tài nguyên mô t bi URL(Uniform Resource Locator)
URLConnection
Biu din kt ni gia vi máy ch biu din bi URL
URLEncoder & URLDecoder
Chuyn i biu din d liu vi các mã d liu khác nhau
ContentHandler:
t ng cp nht phn mm x lý các kiu d liu mi
Ít dùng
Network Programming
- Lp InetAddress
public static InetAddress getByName(String host) throws UnknownHostException
public static InetAddress[] getAllByName(String host) throws UnknownHostException
public static InetAddress getLocalHost() throws UnknownHostException
Kt ni n chng trình DNS cc b ly thông tin
Có th gây ra ngoi l nu kt ni không c phép
Có th t ng kt ni vi bên ngoài
Có th b li dng truyn tin trái phép ra ngoài qua DNS
Network Programming
- Lp InetAddress (2)
public String getHostName()
Tr v a ch IP dng chui ký t/chui byte
public String getHostAddress()
public byte[] getAddress()
Cn chuyn i biu din byte sang int
int unsignedByte = signedByte < 0 ? signedByte + 256 : signedByte;
Xác nh kiu a ch
public boolean isMulticastAddress()
public boolean isLoopbackAddress( )
public boolean equals(Object obj)
i tng obj bng mt i tng InetAddress khi nó là mt phiên bn (instance) InetAddress và có cùng a ch IP
public String toString()
{
host = input.readLine(); /*c chui ký t nhp t bàn phím*/
try
import java.net.*;
{
}
}
}
TCP client
TCP server
Lp Java.net.Socket
Các bc thit lp máy khách
To i tng Socket thit lp kt ni n máy ch s dng Socket()
Thit lp các dòng xut/nhp d liu
Gi và nhn d liu
óng kt ni close()
Lp Java.net.Socket
Lp c bn ca Java thc hin truyn tin TCP gia máy khách và máy ch
Thit lp hoc ngt kt ni và thit lp các tùy chn socket
Kt ni c thit lp khi khi to i tng
Mi i tng Socket c gán vi mt máy ch duy nht
public Socket(String host, int port) throws UnknownHostException, IOException
public Socket(InetAddress address, int port) throws IOException
public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException
public Socket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException
Network Programming
Ly thông tin v mt Socket
Ly thông tin v a ch máy tính kt ni n
public InetAddress getInetAddress( )
public int getPort( )
public int getLocalPort( )
Ly thông tin v a ch kt ni cc b
public InetAddress getLocalAddress( )
Xut nhp d liu socket
Gi và nhn d liu socket c thc hin thông qua dòng d liu xut/nhp
public InputStream getInputStream() throws IOException
tr v i tng InputStream
public OutputStream getOutputStream() throws IOException
tr v i tng OutputStream
Network Programming
public abstract int read( ) throws IOException
public int read(byte[] input) throws IOException
public int read(byte[] input, int offset, int length) throws IOException
public int available( ) throws IOException
Giá tr tr v bng -1 nu n cui dòng d liu
D liu c di dng signed byte
Cn chuyn i signed byte -> unsigned byte
b = in.read( );
Thc hin vòng lp c ht d liu
Network Programming
int bytesRead = 0;
int bytesToRead = 1024;
while (bytesRead < bytesToRead) {
while (bytesRead < bytesToRead) {
bytesRead += result;
public void write(byte[] data) throws IOException
public void write(byte[] data, int offset, int length) throws IOException
public void flush( ) throws IOException
public void close( ) throws IOException
Ghi mt dãy byte hiu qu hn ghi tng byte
Nên s dng hàm flush() lnh ghi c thc hin ngay
Network Programming
Network Programming
Filter Streams
InputStream và OutputStream là các lp x lý d liu thô (byte)
Cn chuyn i d liu thô sang các nh dng d liu nht nh và ngc li
7-bit ASCII, 8-bit Latin-1 hay UTF-8, nh dng zip
Hai loi filter
filter stream: làm vic trên d liu byte
readers and writers: làm vic x lý d liu text vi các kiu encoding khác nhau
Application
InputStreamReader
GZIPInputStream
CipherInputStream
BufferedInputStream
InputStream
Network
public void shutdownInput( ) throws IOException // Java 1.3
public void shutdownOutput( ) throws IOException // Java 1.3
public boolean isInputShutdown( ) // Java 1.4
public boolean isOutputShutdown( ) // Java 1.4
Network Programming
String hostname;
int port;
InputStream timeStream = theSocket.getInputStream( );
} // end try
TCP_NODELAY
public boolean getTcpNoDelay( ) throws SocketException
SO_REUSEADDR // Java 1.4
public boolean getReuseAddress( ) throws SocketException
SO_TIMEOUT
Public int getSoTimeout( ) throws SocketException
SO_LINGER
public int getSoLinger( ) throws SocketException
SO_SNDBUF/ SO_RCVBUF (Java 1.2 and later)
public void setReceiveBufferSize(int size) throws SocketException, IllegalArgumentException
public int getReceiveBufferSize( ) throws SocketException
SO_KEEPALIVE (Java 1.3 and later)
public void setKeepAlive(boolean on) throws SocketException
public boolean getKeepAlive( ) throws SocketException
Network Programming
Lp Java.net.ServerSocket
Các bc thit lp máy ch
To mt i tng ServerSocket s dng hàm khi to ServerSocket( )
ServerSocket ch kt ni t phía máy khách bng hàm accept()
Tr v mt i tng Socket kt ni gia máy khách và máy ch
Thit lp các dòng xut/nhp d liu
Gi và nhn d liu
óng kt ni
Network Programming
Lp Java.net.ServerSocket
Có bn hàm khi to ServerSocket cho phép thit lp cng, kích thc hàng i ca các yêu cu kt ni và network interface gán cho tin trình máy ch
public ServerSocket(int port) throws BindException, IOException
public ServerSocket(int port, int backlog) throws BindException, IOException
public ServerSocket(int port, int backlog, InetAddress bindAddr)
throws BindException, IOException
Network Programming
public Socket accept() throws IOException
Dng thc hin ca tin trình và i kt ni t máy khách
Khi có mt máy khách kt ni n, hàm accept( ) s tr v mt i tng kiu Socket
Chú ý x lý các loi ngoi l khác nhau
public void close() throws IOException
óng socket máy ch và gii phóng cng ch
Network Programming
import java.net.*;
import java.io.*;
import java.util.Date;
public static void main(String[] args) {
int port = DEFAULT_PORT;
if (args.length > 0) {
System.out.println("Port must between 0 and 65535");
return;
public InetAddress getInetAddress( )
public int getLocalPort( )
SO_TIMEOUT
public int getSoTimeout( ) throws IOException
SO_REUSEADDR
public boolean getReuseAddress( ) throws SocketException
SO_RCVBUF
public int getReceiveBufferSize( ) throws SocketException
Network Programming
Network Programming
Cung cp các hàm
Ly và thit lp a ch ích/ngun t/vào tiêu IP
Ly và thit lp cng giao tip ích/ngun
Nhn và thit lp gói d liu UDP
Network Programming
InetAddress a, int port);
Network Programming
To datagram socket nhn DatagramPacket.
Không có phân bit gia socket máy khách và socket máy ch
Mt DatagramSocket có th gi cho nhiu a ch ích khác nhau.
a ch ích c lu ti DatagramPacket
public DatagramSocket() throws SocketException
public DatagramSocket(int port, InetAddress laddr) throws SocketException
Network Programming
public void send(DatagramPacket dp) throws IOException
Gi gói d liu UDP vi i tng kiu DatagramPacket c to ra
public void receive(DatagramPacket dp) throws IOException
Nhn gói d liu UDP và lu li ti i tng kiu DatagramPacket c to ra t trc
public void close( )
Gii phóng cng ang oc s dng bi socket ó
public int getLocalPort( )
Tr v s hiu cng mà socket ang s dng
public InetAddress getLocalAddress( )
Tr v a ch IP mà socket ang s dng
Network Programming
public void connect(InetAddress host, int port)
Gi và nhn gói tin t mt i ch IP và cng c nh trc
Không ging nh kt ni TCP
public void disconnect( )
public int getPort( )
public InetAddress getInetAddress( )
Network Programming
Khi to mt i tng kiu DatagramSocket
DatagramSocket dgramSocket =
new DatagramSocket(1234);
byte[] buffer = new byte[256];
To i tng kiu DatagramPacket cho dòng d liu nhp
DatagramPacket inPacket =
dgramSocket.receive(inPacket)
Các bc thit lp truyn tin UDP - MÁY CH(2)
Ly a ch và cng ca bên gi t gói tin nhn c
InetAddress clientAddress = inPacket.getAddress();
int clientPort = inPacket.getPort();
string message =
DatagramPacket outPacket =
new DatagramPacket(
response.getBytes(), response.length(),
clientAddress, clientPort);
– Máy khách (1)
DatagramSocket dgramSocket = new DatagramSocket;
DatagramPacket outPacket = new DatagramPacket(
byte[] buffer = new byte[256];
Network Programming
– Máy khách (2)
To i tng kiu DatagramPacket cho gói d liu nhp
DatagramPacket inPacket =
dgramSocket.receive(inPacket)
string response = new String(inPacket.getData(), 0, inPacket.getLength());
óng DatagramSocket:
import java.net.*;
import java.io.*;
public static void main(String[] args) {
int port = DEFAULT_PORT;
try {
try {
while (true) {
// packet.setLength(buffer.length); // reset the length for the next packet
}
import java.net.*;
import java.io.*;
public static void main(String[] args) {
String hostname;
try {
DatagramSocket theSocket = new DatagramSocket( );
theSocket.send(theOutput);