首页 > 编程语言 > 详细

java下tcp的socket连接

时间:2015-09-07 22:21:57      阅读:270      评论:0      收藏:0      [点我收藏+]

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();

    }

}

 

java下tcp的socket连接

原文:http://www.cnblogs.com/zywf/p/4789921.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!