简单的socket工具类

Webscoket简单的连接、发送消息和读取服务器返回的消息

#我是刚刚毕业的小白,在公司项目的过程中需要与公司服务器对接socket,模仿写了一个小的简单的socket的工具类,在此写博客是为了加深自己的印象,欢迎各位大神指点,也为同样的小白给出点思路。废话不多说直接贴代码。

public class ScoketUtil {
    /**
     * ip     ip地址
     * port   端口
     * DataOutputStream   输出流
     * DataInputStream    输入流
     * */
    String ip = "192.168.1.115";
    int port = 8001;
    DataOutputStream dos = null;
    Socket soc = null;
    DataInputStream dis = null;
    public static String data;


    public static void setData(String data) {
        ScoketUtil.data = data;
    }

  /**
   * socket  登录
   * */
    public void  Login(){
        new Thread(){
            @Override
            public void run() {
                if (soc == null) {
                    try {
                        soc = new Socket(ip, port);
                        //获取socket的输入输出流
                        dis = new DataInputStream(soc.getInputStream());
                        dos = new DataOutputStream(soc.getOutputStream());
                        setData("user login user=admin;password=admin;");  // 这里需要登录用户名和密码所以要发送登录的指令
                        send();
                        read();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
    }.start();
}
/**
 * 发送消息
 * */
       public void send(){
        new Thread(){
            public  void  run(){
                try {
                    System.out.println(data);
                    soc.getOutputStream().write(data.getBytes());
                    soc.getOutputStream().flush();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
       }
       /**
        * 读取服务器的返回消息
        * */
       public void read(){
           new Thread(){
               public  void  run(){
                   while (true){
                       try {
                           byte[] b = new  byte[1024];
                           soc.getInputStream().read(b);
                           System.out.println(new String(b));
                       } catch (IOException e) {
                           // TODO Auto-generated catch block
                           e.printStackTrace();
                       }
                   }
               }
           }.start();
       }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值