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();
    
        }
    
    }
  • 相关阅读:
    hbuilder(js+html+css)开发的APP效果实例
    基于ServiceStack.OrmLite框架 代码性能、开发效率皆第一 没有之一
    nodejs+IIS+WebMatrix
    小型设备嵌入式开发(.NET Micro Framework)
    SQL对数据进行统计、常用集合函数
    .Net Micro Framework 嵌入式开发
    js+html+css 开发App
    Dos.ORM
    ORM(ServiceStack,Moon,DbEntry,EasyDb,netnorm )
    商业款ORM servicestack llblgen
  • 原文地址:https://www.cnblogs.com/zywf/p/4789921.html
Copyright © 2011-2022 走看看