Socket以及ServerSocket所涉及的异常类型
以下四种类型都是继承于IOException,所以很多之后直接弹出IOException
UnkownHostException: 主机名字或IP错误
ConnectException: 服务器拒绝连接、服务器没有启动、(超出队列数,拒绝连接)
SocketTimeoutException: 连接超时
BindException: Socket对象无法与制定的本地IP地址或端口绑定
交互过程
Socket与ServerSocket的交互
Socket编程Server端5步
1、启动ServerSocket ServerSocket serverSocket=new ServerSocket(post);
2、侦听连接:Socket socket=serverSocket.accept();
3、读取数据:BuffereRead input = new BufferedReader(new InputStreamReader(socket.getInputStream());
String s =intput.readLine();
4、写数据:BuffereWrite input = new BufferedWrite(new OutputStreamWrite(socket.getOutputStream());
intput.write(s,0,s.length());
5、关闭连接:socket.close();
serverSocket.close();
Client端4步
1、启动Server Socket socket = new Socket("localhost",post);
2、读取数据:BuffereRead input = new BufferedReader(new InputStreamReader(socket.getInputStream());
String s =intput.readLine();
3、写数据:BuffereWrite input = new BufferedWrite(new OutputStreamWrite(socket.getOutputStream());
intput.write(s,0,s.length());
4、关闭连接:socket.close();
Socket构造函数
Socket()
Socket(InetAddress address, int port)throws UnknownHostException, IOException
Socket(InetAddress address, int port, InetAddress localAddress, int localPort)throws IOException
Socket(String host, int port)throws UnknownHostException, IOException
Socket(String host, int port, InetAddress localAddress, int localPort)throws IOException
除去第一种不带参数的之外,其它构造函数会尝试建立与服务器的连接。如果失败会抛出IOException错误。如果成功,则返回Socket对象。
InetAddress是一个用于记录主机的类,其静态getHostByName(String msg)可以返回一个实例,其静态方法getLocalHost()也可以获得当前主机的IP地址,并返回一个实例。Socket(String host, int port, InetAddress localAddress, int localPort)构造函数的参数分别为目标IP、目标端口、绑定本地IP、绑定本地端口。
Socket方法
getInetAddress(); 远程服务端的IP地址
getPort(); 远程服务端的端口
getLocalAddress() 本地客户端的IP地址
getLocalPort() 本地客户端的端口
getInputStream(); 获得输入流
getOutStream(); 获得输出流
Socket状态
isClosed(); //连接是否已关闭,若关闭,返回true;否则返回false
isConnect(); //如果曾经连接过,返回true;否则返回false
isBound(); //如果Socket已经与本地一个端口绑定,返回true;否则返回false
如果要确认Socket的状态是否处于连接中,下面语句是很好的判断方式。
boolean isConnection=socket.isConnected() && !socket.isClosed(); //判断当前是否处于连接
ServerSocket构造函数
ServerSocket()throws IOException
ServerSocket(int port)throws IOException
ServerSocket(int port, int backlog)throws IOException
ServerSocket(int port, int backlog, InetAddress bindAddr)throws IOException
注意:
- port服务端要监听的端口;backlog客户端连接请求的队列长度;bindAddr服务端绑定IP
- 如果端口被占用或者没有权限使用某些端口会抛出BindException错误。譬如1~1023的端口需要管理员才拥有权限绑定。
- 如果设置端口为0,则系统会自动为其分配一个端口;
- bindAddr用于绑定服务器IP,为什么会有这样的设置呢,譬如有些机器有多个网卡。
- ServerSocket一旦绑定了监听端口,就无法更改。ServerSocket()可以实现在绑定端口前设置其他的参数。
多线程的ServerSocket实现方式:
主线程会循环执行ServerSocket.accept();
当拿到客户端连接请求的时候,就会将Socket对象传递给多线程,让多线程去执行具体的操作;
实现多线程的方法要么继承Thread类,要么实现Runnable接口。当然也可以使用线程池,但实现的本质都是差不多的。
下面代码为服务器的主线程。为每个客户分配一个工作线程:
try {
System.out.println("正在启动服务。。。。");
ServerSocket serverSocket = new ServerSocket(6666);
while(true){
Socket socket = serverSocket.accept();
System.out.println("连接客户端");
InputThread inputThread = new InputThread(socket);
inputThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
使 InputThread继承自Thread类,并实现InputStram和OutputStram
public class InputThread extends Thread{
Socket socket;
BufferedReader input;
BufferedWriter output;
public InputThread(Socket socket){
this.socket = socket;
try {
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run(){
boolean shouldContinue=true;
while(shouldContinue){
try {
String msg = this.input.readLine();
System.out.println("client:" + msg);
if("bye".equals(msg)) break;
Random random = new Random();
int luckNum = random.nextInt(100);
System.out.println("luckNum" + luckNum);
this.output.write(luckNum + "\r");
this.output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
this.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}