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

    package cn.stat.p4.ipdemo;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    
    import java.io.InputStreamReader;
    
    import java.io.PrintWriter;
    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();
            
            //通过socket对象获取输入流,要读取客户端发过来的数据
            BufferedReader bufin=new BufferedReader(new InputStreamReader(s.getInputStream()));
            
            //4,获取socket的输出流,并装饰。
                    PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        
            String line=null;
                    
            while((line=bufin.readLine())!=null)
            {
                System.out.println(line);
                //发送
                out.println(line.toUpperCase());
                
            }    
            
            s.close();
            ss.close();        
            
    
        }
    
    }
    package cn.stat.p4.ipdemo;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    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);
            
            //获取键盘输入
            BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
            
            
            
            //获取输出流对像
            PrintWriter pw=new PrintWriter(socket.getOutputStream(),true);
            //获取返回数据
            BufferedReader bufin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line=null;
            
            while((line=bufr.readLine())!=null)
            {
                if(line.equals("over"))
                    break;
                System.out.println(line);
                pw.println(line);
                
                String uptext=bufin.readLine();
                System.out.println(uptext);
                
            }
                    
            socket.close();
    
        }
    
    }
  • 相关阅读:
    介绍一种很好用的任务调度平台
    java中的进制与操作符
    类再生(合成、继承、final)
    初始化
    重新学习Spring2——IOC和AOP原理彻底搞懂
    重新学习Spring一--Spring在web项目中的启动过程
    JDK并发包
    java并行程序基础
    MVC模式
    访问者模式
  • 原文地址:https://www.cnblogs.com/zywf/p/4790062.html
Copyright © 2011-2022 走看看