首页 > 其他分享 >Go - Creating a TCP Client

Go - Creating a TCP Client

时间:2023-10-16 14:47:07浏览次数:33  
标签:Creating err TCP client Client address Go net server

Problem: You want to create a TCP client to send data to a TCP server.


Solution: Use the Dial function in the net package to connect to a TCP server.

 

Creating a TCP client is similar to creating a TCP server but even simpler. The main difference is that the client connects to a server instead of listening for connections:

func   main ()   { 
      conn ,   err   :=   net . Dial ( "tcp" ,   ":9000" ) 
      if   err   !=   nil   { 
          log . Fatal ( err ) 
      } 
      defer   conn . Close () 
      conn . Write ([] byte ( "Hello  World  from  TCP  client" )) 
}

First, connect to the server using the net.Dial function. Then write data to the connection; when you’re done you can close the connection.

The net.Dial function returns a net.Conn interface, which is a generic stream - oriented network connection. It is an abstraction of a network connection and has Read and Write methods, meaning it is both a Reader and Writer . In a TCP client, you will use this connection to write data to the server.

Use nc to listen on a port and see what the client sends:

$  nc  - l  9000

Then run the client on another terminal:

$  go  run  main.go

On the nc terminal “Hello World from TCP client” prints out.

How about IPv6? You can use the - 6 flag to force nc to listen on IPv6:

$  nc  - l  - 6  9000

If you run the client again you will see the same output. Go TCP clients send out the data using both IPv4 and IPv6.

Just as you can create a TCP server using the net.ListenTCP and AcceptTCP functions, you can also create a TCP client using the net.DialTCP function:

func   main ()   { 
      addr ,   err   :=   net . ResolveTCPAddr ( "tcp" ,   ":9000" ) 
      if   err   !=   nil   { 
          log . Fatal ( err ) 
      } 
      conn ,   err   :=   net . DialTCP ( "tcp" ,   nil ,   addr ) 
      if   err   !=   nil   { 
          log . Fatal ( err ) 
      } 
      defer   conn . Close () 
      conn . Write ([] byte ( "Hello  World  from  TCP  Client" )) 
}

The net.DialTCP function takes a network string and two net.TCPAddr structs as arguments. You can create the address structs using the net.ResolveTCPAddr function. The first argument to net.DialTCP is the network, followed by the local address and the remote address. If the local address is nil, a local address is automatically chosen. If the remote address is nil, an error is returned.

 

标签:Creating,err,TCP,client,Client,address,Go,net,server
From: https://www.cnblogs.com/zhangzhihui/p/17767275.html

相关文章

  • google gtest框架入门使用案例
    通过本文可以收获:googlegtest急速入门、googlegtest资源网站。googlegtest是什么googlegtest是谷歌开源的c++单元测试框架,非常的好用。起码个人感觉和springboot自带的测试框架功能差不太多。安装略过,请参考:GitHub-google/googletest:GoogleTest-GoogleTesting......
  • mongo_db数据库
    数据库数据服务器下,每次创建一个数据库。userdatabase_name;("没有就会创建---有的话就会切换")并且每个数据库下面又单独的用户。 1--:创建用户:先use到指定的数据库。db.createUser({user:"ems",pwd:"Rxd123456!",//orcleartextpasswordroles:[{......
  • gorm 使用where in 条件查询时,使用uint8[] 类型报错的解决方案
    出现问题:在开发过程中,遇到这样一个问题,GORMModel如下:typeTeststruct{ ... cloumnTypeuint8`gorm:"notnull;default:0"`...}其中有一个类型字段,数据范围是1-10所以使用uint8字段来存储,在查询某些类型的数据时,使用了下面的查询语句varlist[]model.......
  • GO语言中的结构体
    结构体创建、访问与修改定义结构体typeuserstruct{idintscorefloat32enrollmenttime.Timename,addrstring//多个字段类型相同时可以简写到一行里}声明和初始化结构体varuuser//声明,会用相应类型的默认值初始化struct里的每一个字段u=use......
  • GO语言中面向接口编程
    接口的基本概念接口是一组行为规范的集合。typeTransporterinterface{//定义接口。通常接口名以er结尾//接口里面只定义方法,不定义变量move(srcstring,deststring)(int,error)//方法名(参数列表)返回值列表whistle(int)int//参数列表和返回值列表......
  • 轻松掌握组件启动之MongoDB(上):高可用复制集架构环境搭建
    MongoDB复制集复制集架构在生产环境中,强烈不建议使用单机版的MongoDB服务器。原因如下:单机版的MongoDB无法保证系统的可靠性。一旦进程发生故障或是服务器宕机,业务将直接不可用。此外,一旦服务器上的磁盘损坏,数据会直接丢失,而此时并没有任何副本可用。为了确保数据的高可用性和......
  • GO语言中的函数
    函数的基本形式//函数定义。a,b是形参funcargf(aint,bint){ a=a+b}varx,yint=3,6argf(x,y)//函数调用。x,y是实参形参是函数内部的局部变量,实参的值会拷贝给形参。函数定义时的第一个的大括号不能另起一行。形参可以有0个或多个。参数类型相同时可......
  • 树叶识别系统python+Django网页界面+TensorFlow+算法模型+数据集+图像识别分类
    一、介绍树叶识别系统。使用Python作为主要编程语言开发,通过收集常见的6中树叶('广玉兰','杜鹃','梧桐','樟叶','芭蕉','银杏')图片作为数据集,然后使用TensorFlow搭建ResNet50算法网络模型,通过对数据集进行处理后进行模型迭代训练,得到一个识别精度较高的H5模型文件。并基于Dja......
  • ARC167D Good Permutation 题解
    题意给定一个长度为\(N\)的排列\((P_1,P_2,\cdots,P_N)\)。称一个排列\(P\)为“好排列”当且仅当对于所有\(1\leqx\leqN\),都能通过不停地使\(x\leftarrowP_x\)将\(x\)变成\(1\)。通过最小次数操作将\(P\)变成“好排列”,每次操作为交换\(P\)中的两个数\(P_i\)......
  • 为什么Google在JSON响应中添加了`while(1);`?
    内容来自DOChttps://q.houxu6.top/?s=为什么Google在JSON响应中添加了while(1);?为什么Google在(私有)JSON响应前加上while(1);?例如,这是在Google日历中打开和关闭日历时的响应:while(1);[['u',[['smsSentFlag','false'],['hideInvitations','false......