在JAVA中,我们用 ServerSocket、Socket类创建一个套接字连接 ,从套接字得到的结果是一个InputStream以及OutputStream对象,以便将连接作为一个IO流对象对待 。通过IO流可以从流中读取数据或者写数据到流中,读写IO流会有异常IOException产生。
套接字 或插座(socket)是 一种软件 形 式的抽象,用于表达两台机器间一个连接的“终端”。针对一个特定的连接,每台机器上都有一个“套接字”,可以想象它们之间有一条虚拟的“线缆”。JAVA 有两个基于数据流的套接字类:ServerSocket,服务器用它“侦听”进入的连接;Socket,客户端用它初始一次连接。侦听套接字只能接收新的 连接请求,不能接收实际的数据包,即ServerSocket不能接收实际的数据包。
套接字底层是基于TCP的,所以socket的超时和TCP超时是相同的。下面先讨论套接字读写缓冲区,接着讨论连接建立超时、读写超时以及JAVA套接字编程的嵌套异常捕获和一个超时例子程序的抓包示例。
1 socket读写缓冲区
JAVA可以设置读写缓冲区的大小-setReceiveBufferSize(int size), setSendBufferSize(int size)。
2 socket连接建立超时
connect(SocketAddress endpoint, int timeout)
如果在timeout内,连接没有建立成功,在TimeoutException异常被抛出。如果timeout的值小于三次握手的时间,那么Socket连接永远也不会建立。
3 socket读超时
4 socket写超时
5 双重嵌套异常捕获
import java.net.*;
import java.io.*;
public class SocketClientTest
{
public static final int PORT = 8088;
public static void main( String[] args ) throws Exception
{
InetAddress addr = InetAddress.getByName( "127.0.0.1" );
Socket socket = new Socket();
try
{
socket.connect( new InetSocketAddress( addr, PORT ), 30000 );
socket.setSendBufferSize(100);
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream() ) );
int i = 0;
while( true )
{
System.out.println( "client sent --- hello *** " + i++ );
out.write( "client sent --- hello *** " + i );
out.flush();
Thread.sleep( 1000 );
}
}
finally
{
socket.close();
}
}
}
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServerTest
{
public static final int PORT = 8088;
public static final int BACKLOG = 2;
public static void main( String[] args ) throws IOException
{
ServerSocket server = new ServerSocket( PORT, BACKLOG );
System.out.println("started: " + server);
try
{
Socket socket = server.accept();
try
{
BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
String info = null;
while( ( info = in.readLine() ) != null )
{
System.out.println( info );
}
}
finally
{
socket.close();
}
}
finally
{
server.close();
}
}
}
执行上面的程序,在程序运行一会儿之后,断开client和server之间的网络连接,在机器上输出如下:
Server上的输出:
Echoing:client sent -----hello0
Echoing:client sent -----hello1
Echoing:client sent -----hello2
Echoing:client sent -----hello3
Echoing:client sent -----hello4
Echoing:client sent -----hello5
Echoing:client sent -----hello6
---->> 断开了网络连接之后没有数据输出
Client上的输出:
socket default timeout = 0
socket = Socket[addr=/10.15.9.99,port=8088,localport=4691]
begin to read
client sent --- hello *** 0
client sent --- hello *** 1
client sent --- hello *** 2
client sent --- hello *** 3
client sent --- hello *** 4
client sent --- hello *** 5
client sent --- hello *** 6
client sent --- hello *** 7
client sent --- hello *** 8
client sent --- hello *** 9
client sent --- hello *** 10
java.net.SocketException : Connection reset by peer: socket write error
public class JabberClient {
public static void main(String[] args)
throws IOException {
// Passing null to getByName() produces the
// special "Local Loopback" IP address, for
// testing on one machine w/o a network:
InetAddress addr =
InetAddress.getByName("127.0.0.1");
// Alternatively, you can use
// the address or name:
// InetAddress addr =
// InetAddress.getByName("127.0.0.1");
// InetAddress addr =
// InetAddress.getByName("localhost");
System.out.println("addr = " + addr);
Socket socket =
new Socket(addr, JabberServer.PORT);
// Guard everything in a try-finally to make
// sure that the socket is closed:
try {
System.out.println("socket = " + socket);
BufferedReader KeyIn = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Output is automatically flushed
// by PrintWriter:
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())),true);
// for(int i = 0; i < 10; i ++) {
// out.println("howdy " + i);
// String str = in.readLine();
// System.out.println(str);
// }
// out.println("END");
String str =null;
while(true)
{
str = KeyIn.readLine();
if("END".equals(str))
break;
out.println(str);
System.out.println("Server:"+in.readLine());
}
} finally {
System.out.println("closing...");
socket.close();
}
}
} ///:~
public class JabberServer {
// Choose a port outside of the range 1-1024:
public static final int PORT = 8088;
public static void main(String[] args)
throws IOException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("Started: " + s);
try {
Socket socket = s.accept();
try {
System.out.println(
"Connection accepted: "+ socket);
BufferedReader KeyIn = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Output is automatically flushed
// by PrintWriter:
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())),true);
while (true) {
String str = in.readLine();
if (str.equals("END")) break;
System.out.println("Client: " + str);
out.println(KeyIn.readLine());
}
// Always close the two sockets...
} finally {
System.out.println("closing...");
socket.close();
}
} finally {
s.close();
}
}
} ///:~
注意:一般在传输字符信息(例如txt文件,聊天信息)使用bufferedRead,printWrite
UDP的通信建立的步骤
UDP客户端首先向被动等待联系的服务器发送一个数据报文。一个典型的UDP客户端要经过下面三步操作:
1、创建一个DatagramSocket实例,可以有选择地对本地地址和端口号进行设置,如果设置了端口号,则客户端会在该端口号上监听从服务器端发送来的数据;
2、使用DatagramSocket实例的send()和receive()方法来发送和接收DatagramPacket实例,进行通信;
3、通信完成后,调用DatagramSocket实例的close()方法来关闭该套接字。
由于UDP是无连接的,因此UDP服务端不需要等待客户端的请求以建立连接。另外,UDP服务器为所有通信使用同一套接字,这点与TCP服务器不同,TCP服务器则为每个成功返回的accept()方法创建一个新的套接字。一个典型的UDP服务端要经过下面三步操作:
1、创建一个DatagramSocket实例,指定本地端口号,并可以有选择地指定本地地址,此时,服务器已经准备好从任何客户端接收数据报文;
2、使用DatagramSocket实例的receive()方法接收一个DatagramPacket实例,当receive()方法返回时,数据报文就包含了客户端的地址,这样就知道了回复信息应该发送到什么地方;
3、使用DatagramSocket实例的send()方法向服务器端返回DatagramPacket实例。
一. UDP协议定义UDP协议的全称是用户数据报,在网络中它与TCP协议一样用于处理数据包。在OSI模型中,在第四层——传输层,处于IP协议的上一层。UDP有不提供数据报分组、组装和不能对数据包的排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的。
二. 使用UDP的原因
它不属于连接型协议,因而具有资源消耗小,处理速度快的优点,所以通常音频、视频和普通数据在传送时使用UDP较多,因为它们即使偶尔丢失一两个数据包,也不会对接收结果产生太大影响。比如我们聊天用的ICQ和OICQ就是使用的UDP协议。在选择使用协议的时候,选择UDP必须要谨慎。在网络质量令人不十分满意的环境下,UDP协议数据包丢失会比较严重。
三. 在Java中使用UDP协议编程的相关类
1. InetAddress
用于描述和包装一个Internet IP地址。有如下方法返回实例:
getLocalhost():返回封装本地地址的实例。
getAllByName(String host):返回封装Host地址的InetAddress实例数组。
getByName(String host):返回一个封装Host地址的实例。其中,Host可以是域名或者是一个合法的IP地址。
InetAddress.getByAddress(addr):根据地址串返回InetAddress实例。
InetAddress.getByAddress(host, addr):根据主机地符串和地址串返回InetAddress实例。
2. DatagramSocket
用于接收和发送UDP的Socket实例。该类有3个构造函数:
DatagramSocket():通常用于客户端编程,它并没有特定监听的端口,仅仅使用一个临时的。程序会让操作系统分配一个可用的端口。
DatagramSocket(int port):创建实例,并固定监听Port端口的报文。通常用于服务端
DatagramSocket(int port, InetAddress localAddr):这是个非常有用的构建器,当一台机器拥有多于一个IP地址的时候,由它创建的实例仅仅接收来自LocalAddr的报文。
DatagramSocket具有的主要方法如下:
1)receive(DatagramPacket d):接收数据报文到d中。receive方法产生一个“阻塞”。“阻塞”是一个专业名词,它会产生一个内部循环,使程序暂停在这个地方,直到一个条件触发。
2)send(DatagramPacket dp):发送报文dp到目的地。
3)setSoTimeout(int timeout):设置超时时间,单位为毫秒。
4)close():关闭DatagramSocket。在应用程序退出的时候,通常会主动释放资源,关闭Socket,但是由于异常地退出可能造成资源无法回收。所以,应该在程序完成时,主动使用此方法关闭Socket,或在捕获到异常抛出后关闭Socket。
3. DatagramPacket
用于处理报文,它将Byte数组、目标地址、目标端口等数据包装成报文或者将报文拆卸成Byte数组。应用程序在产生数据包是应该注意,TCP/IP规定数据报文大小最多包含65507个,通常主机接收548个字节,但大多数平台能够支持8192字节大小的报文。DatagramPacket类的构建器共有4个:
DatagramPacket(byte[] buf, int length):将数据包中Length长的数据装进Buf数组,一般用来接收客户端发送的数据。
DatagramPacket(byte[] buf, int offset, int length):将数据包中从Offset开始、Length长的数据装进Buf数组。
DatagramPacket(byte[] buf, int length, InetAddress clientAddress, int clientPort):从Buf数组中,取出Length长的数据创建数据包对象,目标是clientAddress地址,clientPort端口,通常用来发送数据给客户端。
DatagramPacket(byte[] buf, int offset, int length, InetAddress clientAddress, int clientPort):从Buf数组中,取出Offset开始的、Length长的数据创建数据包对象,目标是clientAddress地址,clientPort端口,通常用来发送数据给客户端。
主要的方法如下:
1)getData(): 从实例中取得报文的Byte数组编码。
2)setDate(byte[] buf):将byte数组放入要发送的报文中。
四. 实例解析
下面让我们来看一个UDP的服务端和客户端交互通信的例子,在本例中,服务端循环等待客户端发送的信息,并对其进行回应,客户端向服务端发送信息,并接收服务端的回应信息。代码如下:
1.UDP的服务端程序
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
/**
* Copyright 2007 GuangZhou Cotel Co. Ltd.
* All right reserved.
* UTP服务类.
* @author QPING
*/
public class UdpServerSocket {
private byte[] buffer = new byte[1024];
private DatagramSocket ds = null;
private DatagramPacket packet = null;
private InetSocketAddress socketAddress = null;
private String orgIp;
/**
* 构造函数,绑定主机和端口.
* @param host 主机
* @param port 端口
* @throws Exception
*/
public UdpServerSocket(String host, int port) throws Exception {
socketAddress = new InetSocketAddress(host, port);
ds = new DatagramSocket(socketAddress);
System.out.println("服务端启动!");
}
public final String getOrgIp() {
return orgIp;
}
/**
* 设置超时时间,该方法必须在bind方法之后使用.
* @param timeout 超时时间
* @throws Exception
*/
public final void setSoTimeout(int timeout) throws Exception {
ds.setSoTimeout(timeout);
}
/**
* 获得超时时间.
* @return 返回超时时间.
* @throws Exception
*/
public final int getSoTimeout() throws Exception {
return ds.getSoTimeout();
}
/**
* 绑定监听地址和端口.
* @param host 主机IP
* @param port 端口
* @throws SocketException
*/
public final void bind(String host, int port) throws SocketException {
socketAddress = new InetSocketAddress(host, port);
ds = new DatagramSocket(socketAddress);
}
/**
* 接收数据包,该方法会造成线程阻塞.
* @return 返回接收的数据串信息
* @throws IOException
*/
public final String receive() throws IOException {
packet = new DatagramPacket(buffer, buffer.length);
ds.receive(packet);
orgIp = packet.getAddress().getHostAddress();
String info = new String(packet.getData(), 0, packet.getLength());
System.out.println("接收信息:" + info);
return info;
}
/**
* 将响应包发送给请求端.
* @param bytes 回应报文
* @throws IOException
*/
public final void response(String info) throws IOException {
System.out.println("客户端地址 : " + packet.getAddress().getHostAddress()
+ ",端口:" + packet.getPort());
DatagramPacket dp = new DatagramPacket(buffer, buffer.length, packet
.getAddress(), packet.getPort());
dp.setData(info.getBytes());
ds.send(dp);
}
/**
* 设置报文的缓冲长度.
* @param bufsize 缓冲长度
*/
public final void setLength(int bufsize) {
packet.setLength(bufsize);
}
/**
* 获得发送回应的IP地址.
* @return 返回回应的IP地址
*/
public final InetAddress getResponseAddress() {
return packet.getAddress();
}
/**
* 获得回应的主机的端口.
* @return 返回回应的主机的端口.
*/
public final int getResponsePort() {
return packet.getPort();
}
/**
* 关闭udp监听口.
*/
public final void close() {
try {
ds.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 测试方法.
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String serverHost = "127.0.0.1";
int serverPort = 3344;
UdpServerSocket udpServerSocket = new UdpServerSocket(serverHost, serverPort);
while (true) {
udpServerSocket.receive();
udpServerSocket.response("你好,sterning!");
}
}
}
2. UDP客户端程序
import java.io.*;
import java.net.*;
/**
* Copyright 2007 GuangZhou Cotel Co. Ltd.
* All right reserved.
* UDP客户端程序,用于对服务端发送数据,并接收服务端的回应信息.
* @author QPING
*/
public class UdpClientSocket {
private byte[] buffer = new byte[1024];
private DatagramSocket ds = null;
/**
* 构造函数,创建UDP客户端
* @throws Exception
*/
public UdpClientSocket() throws Exception {
ds = new DatagramSocket();
}
/**
* 设置超时时间,该方法必须在bind方法之后使用.
* @param timeout 超时时间
* @throws Exception
*/
public final void setSoTimeout(final int timeout) throws Exception {
ds.setSoTimeout(timeout);
}
/**
* 获得超时时间.
* @return 返回超时时间
* @throws Exception
*/
public final int getSoTimeout() throws Exception {
return ds.getSoTimeout();
}
public final DatagramSocket getSocket() {
return ds;
}
/**
* 向指定的服务端发送数据信息.
* @param host 服务器主机地址
* @param port 服务端端口
* @param bytes 发送的数据信息
* @return 返回构造后俄数据报
* @throws IOException
*/
public final DatagramPacket send(final String host, final int port,
final byte[] bytes) throws IOException {
DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress
.getByName(host), port);
ds.send(dp);
return dp;
}
/**
* 接收从指定的服务端发回的数据.
* @param lhost 服务端主机
* @param lport 服务端端口
* @return 返回从指定的服务端发回的数据.
* @throws Exception
*/
public final String receive(final String lhost, final int lport)
throws Exception {
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String info = new String(dp.getData(), 0, dp.getLength());
return info;
}
/**
* 关闭udp连接.
*/
public final void close() {
try {
ds.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 测试客户端发包和接收回应信息的方法.
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
UdpClientSocket client = new UdpClientSocket();
String serverHost = "127.0.0.1";
int serverPort = 3344;
client.send(serverHost, serverPort, ("你好,阿蜜果!").getBytes());
String info = client.receive(serverHost, serverPort);
System.out.println("服务端回应数据:" + info);
}
}