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();
    
        }
    
    }
  • 相关阅读:
    【转】 C++模板详解
    【转】 memcmp源码实现
    【转】 C++的精髓——虚函数
    【转】 如何使用Valgrind memcheck工具进行C/C++的内存泄漏检测
    【转】 优秀代码所具备的5大品质
    爬取贴吧中的html,并保存到相对应的文件夹中
    urllib模块通过post请求获取数据
    django,uwsgi, nginx部署项目
    Django中Ajax处理
    Django中的session于cookie的用法
  • 原文地址:https://www.cnblogs.com/zywf/p/4789921.html
Copyright © 2011-2022 走看看