26-网络编程-12-网络编程(TCP协议-服务端和客户端交互)

/*
 * 【需求】客户端和服务端进行交互,类似于QQ聊天形式,互相发送接收信息。
 * 图解详见桌面文件26Internet12,客户端out数据对应服务端in数据,服务端out数据对应客户端in数据
 */

package demo;

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

public class ClientDemo {

	public static void main(String[] args) throws UnknownHostException, IOException {

		Socket socket = new Socket("10.196.19.56",10002);
		
		OutputStream out = socket.getOutputStream();
		
		out.write("TCP演示......".getBytes());
		
		//读取服务端反馈的数据,使用Socket输入流
		InputStream in = socket.getInputStream();//由于是服务端发出的数据,这里需要in进客户端
		byte[] buf = new byte[1024];
		int len = in.read(buf);
		String text = new String(buf,0,len);
		
		System.out.println(text);
		
		socket.close();
		
		
		
	}

}

========================分割线=================================

package demo;

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

public class ServerDemo {

	public static void main(String[] args) throws IOException {

		ServerSocket ss = new ServerSocket(10002);
		
		Socket s = ss.accept();//阻塞式:没客户端连过来就一直等
		
		String ip = s.getInetAddress().getHostAddress();
		
		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+":"+text);
		//以上是接收客户端发来的数据,对应图解in进来
		
		//使用Socket的输出流,给客户端反馈数据,对应图解out出去
		OutputStream out = s.getOutputStream();
		out.write("收到......".getBytes());
		
		s.close();
		ss.close();
		
	}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值