码迷,mamicode.com
首页 > 编程语言 > 详细

java下tcp的socket连接案例

时间:2015-09-07 22:42:02      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:

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下tcp的socket连接案例

标签:

原文地址:http://www.cnblogs.com/zywf/p/4790062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!