网络通信3:TCP交互通信

栏目: 服务器 · 发布时间: 7年前

内容简介:版权声明:本文为博主尹成联系QQ77025077,微信18510341407原创文章,欢迎转载侵权不究。 https://blog.csdn.net/yincheng01/article/details/84135860

版权声明:本文为博主尹成联系QQ77025077,微信18510341407原创文章,欢迎转载侵权不究。 https://blog.csdn.net/yincheng01/article/details/84135860

服务端实现

import (
	"fmt"
	"net"
	"os"
	"strings"
)

func CheckErrorS(err error) {
	if err != nil {
		fmt.Println("网络错误", err.Error())
		os.Exit(1)
	}
}

func Processinfo(conn net.Conn) {
	buffer := make([]byte, 1024) //开创缓冲区
	defer conn.Close()           //关闭连接

	for {
		n, err := conn.Read(buffer) //读取数据
		CheckErrorS(err)

		if n != 0 {
			//拿到客户端地址
			remoteAddr := conn.RemoteAddr()
			msg := string(buffer[:n])
			fmt.Println("收到消息",msg, "来自", remoteAddr)

			if strings.Contains(msg,"钱") {
				conn.Write([]byte("fuckoff"))
				break
			}
			conn.Write([]byte("已阅:"+msg))
		}
	}

}

func main() {
	//建立TCP服务器
	listener, err := net.Listen("tcp", "127.0.0.1:8898")
	CheckErrorS(err)
	defer listener.Close() //关闭网络

	fmt.Println("服务器正在等待")

	for {
		conn, err := listener.Accept() //新的客户端连接
		CheckErrorS(err)

		//处理每一个客户端
		go Processinfo(conn)
	}

}

客户端实现

import (
	"fmt"
	"net"
	"bufio"
	"os"
)

func CheckErrorC(err error) {
	if err != nil {
		fmt.Println("网络错误", err.Error())
		os.Exit(1)
	}
}

func MessageSend(conn net.Conn) {
	var msg string
	reader := bufio.NewReader(os.Stdin) //读取键盘输入

	for {
		lineBytes, _, _ := reader.ReadLine() //读取一行
		msg = string(lineBytes)              //键盘输入转化为字符串

		if msg == "exit" {
			conn.Close()
			fmt.Println("客户端关闭")
			break
		}

		_, err := conn.Write([]byte(msg)) //输入写入字符串
		if err != nil {
			conn.Close()
			fmt.Println("客户端关闭")
			break
		}

	}
}

func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:8898") //建立TCP服务器
	CheckErrorC(err)                               //检查错误
	defer conn.Close()

	//发送消息中有阻塞读取标准输入的代码
	//为了避免阻塞住消息的接收,所以把它独立的协程中
	go MessageSend(conn)

	buffer := make([]byte, 1024)
	for {
		n, err := conn.Read(buffer)
		CheckErrorC(err)

		msg := string(buffer[:n])
		fmt.Println("收到服务器消息", msg)

		if msg=="fuckoff"{
			break
		}

	}

	fmt.Println("连接已断开")
}

学院 Go 语言视频主页

https://edu.csdn.net/lecturer/1928

[清华团队带你实战区块链开发]

( https://ke.qq.com/course/344443?tuin=3d17195d )

扫码获取海量视频及源码 QQ群:721929980

网络通信3:TCP交互通信

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Agile Web Application Development with Yii 1.1 and PHP5

Agile Web Application Development with Yii 1.1 and PHP5

Jeffrey Winesett / Packt Publishing / 2010-08-27

In order to understand the framework in the context of a real-world application, we need to build something that will more closely resemble the types of applications web developers actually have to bu......一起来看看 《Agile Web Application Development with Yii 1.1 and PHP5》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

URL 编码/解码
URL 编码/解码

URL 编码/解码