tcp的使用

来源:互联网 发布:js true false 编辑:程序博客网 时间:2024/06/06 02:21
package TCPDemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPCiceiveDemo {

    public static void main(String[] args) throws IOException, IOException {
        //1 创建客户端socket服务;
        Socket client = new Socket("127.0.0.1", 10002);
        //2 获取socket流中的输出流;
        OutputStream os=client.getOutputStream();
        //3 使用输出流将输出的数据传出去;
        os.write("输入的数据".getBytes());
        // 4使用socket读取流读取服务器返回的数据
        InputStream is=client.getInputStream();
        byte[] buf=new byte[1024];
        int len=is.read(buf);
        String str=new String(buf,0,len);
        System.out.println(str);
        //4 关闭资源
        client.close();

    }

class TCPServerDemo {

    public static void main(String[] args) throws IOException {
        //1 建立服务器端对象;
        ServerSocket socket=new ServerSocket(10002);
        //2 获取链接过来的客户端对象;
        Socket client=socket.accept();
        String ip=client.getInetAddress().getHostAddress();
        //3 通过客户端获得输入流,读取发过来的数据;
        InputStream in=client.getInputStream();
        byte[] buf=new byte[1024];
        int len=in.read(buf);
        String text=new String(buf,0,len);
        System.out.println(ip+":"+text);
        //通过socket流将文本发送到客户端;
        OutputStream os=client.getOutputStream();
        os.write("收到了".getBytes());
        //关闭资源
        client.close();
    }


}


0 0
原创粉丝点击