码迷,mamicode.com
首页 > 编程语言 > 详细

Go语言网络通信---tcp群发消息

时间:2020-04-21 16:53:33      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:ack   error   accept   cep   highlight   pac   ror   byte   lis   

server

package main

import (
	"fmt"
	"net"
	"os"
	"time"
)

func SHandleError(err error, when string)  {
	if err != nil{
		fmt.Println("err=", err, when)
		os.Exit(1)
	}
}

func main() {
	listener, e := net.Listen("tcp", ":8080")
	SHandleError(e,"net.Listen")

	conns := make([]net.Conn, 0)

	for len(conns) < 3 {
		conn, e := listener.Accept()
		SHandleError(e, "listener.Accept")
		conns = append(conns, conn)

	}
	fmt.Println("已接入3个客户端,即将群发消息")
	time.Sleep(time.Second*1)
	for _,conn:=range conns{
		msg := fmt.Sprintf("hello!%v", conn.RemoteAddr())
		conn.Write([]byte(msg))
	}

	var userInput = ""
	fmt.Scan(&userInput)
}

 

client

package main

import (
	"fmt"
	"net"
	"os"
)
func CHandleError(err error, when string)  {
	if err != nil{
		fmt.Println("err=", err, when)
		os.Exit(1)
	}
}
func main() {
	conn, e := net.Dial("tcp", "127.0.0.1:8080")
	CHandleError(e, "net.Dial")
	defer func() {
		conn.Close()
		fmt.Println("客户端已退出")
	}()

	buffer := make([]byte, 1024)
	n, e := conn.Read(buffer)
	CHandleError(e ,"conn.Read")
	msg := buffer[:n]
	fmt.Println(string(msg))
}

  

Go语言网络通信---tcp群发消息

标签:ack   error   accept   cep   highlight   pac   ror   byte   lis   

原文地址:https://www.cnblogs.com/yunweiqiang/p/12745575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!