zoukankan      html  css  js  c++  java
  • java下tcp的socket连接

    serverDemo

    package cn.stat.p4.ipdemo;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class serverDemo {
    
        /**
         * @param args
         * @throws IOException 
         */
        public static void main(String[] args) throws IOException {
            //创建服务器对像
            ServerSocket ss=new ServerSocket(1000);
            //获取连接过来的客户端对像
            Socket s=ss.accept();
            
            String ip=s.getInetAddress().getHostAddress();
            int port=s.getPort();
            
            //通过socket对象获取输入流,要读取客户端发过来的数据
            InputStream in=s.getInputStream();
            
            byte[] buf=new byte[1024];
            
            int len=in.read(buf);
            String text=new String(buf,0,len);
            System.out.println(ip+":"+port+":"+text);
            
            //使用客户端的socket对象传输数据回客户端
            OutputStream out=s.getOutputStream();
            out.write("收到".getBytes());
            
            s.close();
            ss.close();
    
        }
    
    }

    clentDemo

    package cn.stat.p4.ipdemo;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class clentDemo {
    
        /**
         * @param args
         * @throws IOException 
         * @throws UnknownHostException 
         */
        public static void main(String[] args) throws UnknownHostException, IOException {
            //创建连接对像
            Socket socket=new Socket("192.168.1.103",1000);
            //获取流对像
            OutputStream out=socket.getOutputStream();
            
            out.write("我又来了".getBytes());
            
            //读取服务端返回数据
            InputStream in=socket.getInputStream();
            byte[] buf=new byte[1024];
            
            int len=in.read(buf);
            
            String text=new String(buf,0,len);
            System.out.println(text);
            
            socket.close();
    
        }
    
    }
  • 相关阅读:
    【转】PowerManager 与 WakeLock
    【转】设计模式总结之模式分类
    【转】一篇文章,教你学会Git
    【转】Iconfont
    【转】码云source tree 提交超过100m 为什么大文件推不上去
    各 Android 平台版本支持的 API 级别
    【转】Android进程机制
    【转】数据库CRUD操作
    【转】数据库--视图的基本概念以及作用
    动态规划的两种形式
  • 原文地址:https://www.cnblogs.com/zywf/p/4789921.html
Copyright © 2011-2022 走看看