此类实现客户端套接字(也可以就叫“套接字”)。套接字是两台机器之间的通信端点。

 

Socket client = new Socket(ip,port);//创建一个流套接字并将其连接到指定 IP 地址的指定端口号。

以下为完整的客户端示例:

SocketClientDemo.java

public class SocketClientDemo 
{
    /**
     * 向指定的地址发送请求数据
     * @param ipAddr
     * @param reqData
     */
    public void sendReq(String ipAddr,String reqData)
    {
        Socket client = null;
        BufferedReader br = null;
        BufferedOutputStream bos = null;
        String respStr = "";
        
        //设置字符集编码格式
        String characterCoding = "GBK";
        
        //将ip:port 类型的字符串拆分
        int dotPos = ipAddr.indexOf(":");
        String ip = ipAddr.substring(0, dotPos).trim();
        int port = Integer.parseInt(ipAddr.substring(dotPos+1).trim());
        
        try 
        {
            client = new Socket(ip,port);
            //设置发送等待时间(单位:s)
            client.setSoLinger(true, 5);
            
            //设置超时时间(单位:ms)
            client.setSoTimeout(5000);
            
            //从client端获取输出流
            bos = new BufferedOutputStream(client.getOutputStream());
            bos.write(reqData.getBytes(characterCoding));
            bos.flush();
            
            br = new BufferedReader(new InputStreamReader(client.getInputStream()));
            respStr = br.readLine();
            System.out.println("respStr is:>>>>>>"+respStr);
        }
        catch (UnknownHostException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(br != null)
            {
                try 
                {
                    br.close();
                }
                catch (IOException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(bos!=null)
            {
                try 
                {
                    bos.close();
                }
                catch (IOException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(client!=null)
            {
                try 
                {
                    client.close();
                }
                catch (IOException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
View Code

相关文章:

  • 2021-10-17
  • 2021-05-16
  • 2021-06-13
  • 2022-02-09
  • 2021-07-23
  • 2022-12-23
猜你喜欢
  • 2021-12-30
  • 2021-08-19
  • 2021-12-03
  • 2021-09-06
  • 2021-11-25
  • 2022-01-04
  • 2021-08-22
相关资源
相似解决方案