tcp的传输

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

/**
 * 演示tcp的传输的客服端和服务端的互访
 * 需求:客服端给服务端发送数据,,服务端接收,给客服端反馈信息
 * @author Administrator
 *
 */
/**
 * 客服端:
 * 1.建立socket服务,指定要连接主机和端口
 * 2.获取socket流中的输出流,将数据写到该流中,通过网络发送给服务端
 * 3.获取socket流中的输入流,将服务端反馈的数据获取,并打印
 * 4.关闭资源
 *
 * @author Administrator
 *
 */
public class TcpClient2 {

 public static void main(String[] args) throws Exception, Exception {
  Socket s=new Socket("192.168.1.254",10004);
  OutputStream out=(OutputStream) s.getOutputStream();
  out.write("".getBytes());
  InputStream in=s.getInputStream();
  byte[] buf=new byte[1024];
  int len=in.read(buf);
  System.out.println(new String(buf,0,len));
  s.close();
 }
}
class TcpServer2{
 public static void main(String[] args) throws Exception {
  ServerSocket ss=new ServerSocket(10004);
  Socket s=ss.accept();
  String ip=s.getInetAddress().getHostAddress();
  InputStream in=s.getInputStream();
  byte[] buf=new byte[1024];
  int len=in.read(buf);
  OutputStream out= s.getOutputStream();
  out.write("".getBytes());
  s.close();
  ss.close();
  out.close();
 }
}

转载于:https://my.oschina.net/u/2329247/blog/389018

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值