首页 > 其他 > 详细

Socket与ServerSocket的应用

时间:2019-10-11 20:03:45      阅读:100      评论:0      收藏:0      [点我收藏+]

Socket

Socket用于客户程序与服务程序之间的TCP连接,实例化一个Socket对象作为端口,其实例为:

package com;
import java.net.*;
import java.io.*;
 /*socket客户端实例*/
public class GreetingClient
{
   public static void main(String [] args)
   {
      String serverName = args[0];
      int port = Integer.parseInt(args[1]);
      try
      {
         System.out.println("连接到主机:" + serverName + " ,端口号:" + port);
         /*创建一个socket对象,serverName服务端IP地址,port服务端端口号*/
         Socket client = new Socket(serverName, port);
         /**返回服务端IP地址*/
         System.out.println("远程主机地址:" + client.getRemoteSocketAddress());
         /*返回输出流*/
         OutputStream outToServer = client.getOutputStream();
         
         DataOutputStream out = new DataOutputStream(outToServer);
         /*发送信息*/
         out.writeUTF("Hello from " + client.getLocalSocketAddress());
         /*返回输入流*/
         InputStream inFromServer = client.getInputStream();
         DataInputStream in = new DataInputStream(inFromServer);
         /*readUTF()读取信息*/
         System.out.println("服务器响应: " + in.readUTF());
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

ServerSocket用作服务端,用来监听客户端的请求,使用accept方法的返回值获得一个socket对象,其实例为

package com;

import java.net.*;
import java.io.*;

/*服务端实例,用来监听一个端口*/
public class GreetingServer extends Thread {
    public ServerSocket serversocket;

    /********
     * 建一个以端口作为参数的构造函数
     * 
     * @throws IOException
     **/
    public GreetingServer(int port) throws IOException {
        serversocket = new ServerSocket(port);
        serversocket.setSoTimeout(10000);
        /**
         * setSoTimeout()这个方法所设置的超时时间还未结束的时候,
         * 可以通过socket.getInputStream()获得的InputStream对象进行二次读取。
         * 在二次读取的时候,如果客户端如果没有进行二次请求,InputStream对象二次读取的时候会死锁
         * ,直到客户端二次请求时才会继续运行,但是一旦超过setSoTimeout()方法所设置的超时时间,
         * 便会抛出java.net.SocketTimeoutException: Read timed out异常。
         * 也就是说两次请求间隔时间如果超过setSoTimeout()方法设置的超时时间,就会抛出异常,
         *  结束InputStream的二次读取
         */
    }
    public void run() {
        while (true) {
            try {
                System.out.println("等待远程连接...端口号为"+serversocket.getLocalPort());
                /*使用accept方法的返回值来获得一个对象*/
                Socket server=serversocket.accept();
                DataInputStream Server=new DataInputStream(server.getInputStream());
                System.out.println("谢谢连接我"+Server.readUTF());
                DataOutputStream outserver=new DataOutputStream(server.getOutputStream());
                outserver.writeUTF("拜拜");
                server.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    }
    public static void main(String[] args) {
        try {
            Thread server=new GreetingServer(Integer.parseInt(args[0]));
            server.run();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

客户端与服务端建立连接时可大致分为四步

1.实例化一个socket对象

2.获得输入或输出流

3.读取或发送消息

4.关闭端口

Socket方法

getInetAddress();      远程服务端的IP地址
getPort();          远程服务端的端口
getLocalAddress()      本地客户端的IP地址
getLocalPort()        本地客户端的端口
getInputStream();     返回与调用的套接字相关联的输入流
getOutStream();      返回与调用的套接字相关联的输出流
值得注意的是,在这些方法里面,最重要的就是getInputStream()和getOutputStream()了。
 
Socket状态
isClosed();            //连接是否已关闭,若关闭,返回true;否则返回false
isConnect();      //如果曾经连接过,返回true;否则返回false
isBound();            //如果Socket已经与本地一个端口绑定,返回true;否则返回false

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对象,以最后一个为例,host,port为远程服务器的IP地址和端口,localAddress和localPort绑定本地IP和端口
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

ServerSocket中有两个方法要特别注意

getInetAddress()用来返回此套接字的IP地址

getlocalport()返回被监听的接口

 

Socket与ServerSocket的应用

原文:https://www.cnblogs.com/19990911-ZXX/p/11656206.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!