zoukankan      html  css  js  c++  java
  • golang 简易tcpserver和tcpclient

    golang 简易tcpserver和tcpclient

    server端代码

    package main
    
    import (
    	"flag"
    	"fmt"
    	"net"
    	"strconv"
    )
    
    //Port 端口
    var Port string
    
    func main() {
    
    	fmt.Println("process start...")
    	flag.StringVar(&Port, "p", "", "proc port")
    	flag.Parse()
    	if Port == "" {
    		fmt.Print("port is null
    ")
    		return
    	}
    
    	p, err := strconv.Atoi(Port)
    
    	if err != nil {
    		fmt.Printf("port is not number and err:[%v]
    ", err)
    		return
    	}
    
    	addr := fmt.Sprintf("0.0.0.0:%d", p)
    	listener, err := net.Listen("tcp", addr)
    	if err != nil {
    		fmt.Printf("err! addr %s open faild err:[%v]
    ", addr, err)
    		return
    	}
    
    	for {
    
    		conn, err := listener.Accept()
    		if err != nil {
    			fmt.Printf("listen err:[%v]
    ", err)
    		}
    
    		go handConn(conn)
    	}
    
    }
    
    func handConn(conn net.Conn) {
    	defer func() {
    		fmt.Printf("client [%s] close
    ", conn.RemoteAddr().String())
    		conn.Close()
    	}()
    	var buf [1024]byte
    	for {
    		n, err := conn.Read(buf[:])
    		if err != nil {
    			fmt.Printf("read from %s msg faild err:[%v]
    ", conn.RemoteAddr().String(), err)
    			break
    		}
    		fmt.Printf("rev data from %s msg:%s
    ", conn.RemoteAddr().String(), string(buf[:n]))
    	}
    
    }
    

    客户端代码

    package main
    
    import (
    	"bufio"
    	"flag"
    	"fmt"
    	"net"
    	"os"
    )
    
    var (
    	addr string
    	port int
    )
    
    func main() {
    	flag.StringVar(&addr, "addr", "", "server ip address")
    	flag.IntVar(&port, "p", 0, "server port")
    	flag.Parse()
    
    	if addr == "" || port == 0 {
    		fmt.Printf("input params error addr:[%s] port:[%d]
    ", addr, port)
    	}
    
    	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", addr, port))
    	defer conn.Close()
    	if err != nil {
    		fmt.Printf("connected server [%s] faild err:%v
    ", addr, err)
    		return
    	}
    	input := bufio.NewReader(os.Stdin)
    	for {
    		bytes, _, err := input.ReadLine()
    		if err != nil {
    			fmt.Printf("read line faild err:%v
    ", err)
    		}
    		str := string(bytes)
    		if str == "Q" || str == "q" {
    			fmt.Println("exe quit!")
    			break
    		}
    		n, err := conn.Write(bytes)
    		if err != nil {
    			fmt.Printf("send data faild err:%v
    ", err)
    		} else {
    			fmt.Printf("send data length %d
    ", n)
    		}
    	}
    
    }
  • 相关阅读:
    正则表达式进阶——你从没想过的正则表达式使用方式
    bert 预训练模型路径
    Ubuntu 18.04 美化
    循环中存在异步的情况
    SQL truncate 、delete与drop区别
    用express创建网站出现"$ DEBUG=microbog ./bin/www"的提示
    全局安装了express框架,但是无法使用express指令的问题
    jQuery获取textarea中的文本
    js实现查询关键词,使其高亮
    SQL Server常用函数汇总
  • 原文地址:https://www.cnblogs.com/wuyaxiansheng/p/13521552.html
Copyright © 2011-2022 走看看