Go语言学习笔记21.socket编程

socket编程分为TCP和UDP的,和C的套接字编程原理一样。
可以参考:https://blog.csdn.net/happy_teemo/article/details/78441982

TCP

服务端:

package main

import (
	"fmt"
	"net"
)

func main() {
	//监听
	listener, err := net.Listen("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("err = ", err)
		return
	}

	//关闭监听
	defer listener.Close()

	//阻塞等待用户链接
	conn, err := listener.Accept()
	if err != nil {
		fmt.Println("err = ", err)
		return
	}

	//接收用户的请求
	buf := make([]byte, 1024) //1024大小的缓冲区
	n, err1 := conn.Read(buf)
	if err1 != nil {
		fmt.Println("err1 = ", err1)
		return
	}

	fmt.Println("buf = ", string(buf[:n]))

	defer conn.Close() //关闭当前用户链接
}

客户端:

package main

import (
	"fmt"
	"net"
)

func main() {
	//主动连接服务器
	conn, err := net.Dial("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("err = ", err)
		return
	}

	//延时关闭
	defer conn.Close()

	//发送数据
	conn.Write([]byte("你好"))

}

UDP

服务端不用和客户端握手连接了

package main

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

func main() {

	addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("Can't resolve address: ", err)
		os.Exit(1)
	}

	//监听
	listener, err := net.ListenUDP("udp", addr)
	if err != nil {
		fmt.Println("err = ", err)
		return
	}

	//关闭监听
	defer listener.Close()

	//接收用户的请求
	for {
		data := make([]byte, 1024)
		n, remoteAddr, err := listener.ReadFromUDP(data)
		if err != nil {
			fmt.Println("failed to read UDP msg because of ", err.Error())
			return
		}
		fmt.Println(n, remoteAddr)//长度和IP
		fmt.Println("buf = ", string(data[:n])) //打印内容
	}
}

客户端:

package main

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

func main() {
	//主动连接服务器
	addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("Can't resolve address: ", err)
		os.Exit(1)
	}
	conn, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		fmt.Println("Can't dial: ", err)
		os.Exit(1)
	}

	//延时关闭
	defer conn.Close()

	//发送数据
	conn.Write([]byte("你好"))

}

你可能感兴趣的:(Go)