zoukankan      html  css  js  c++  java
  • golang学习笔记之tcp简单实现:server端与client端

    server端

    main.go

    package main
    
    import (
    	"fmt"
    	"net"
    )
    
    func main() {
    	//   simple tcp server
    	//1.listen ip+port
    	listener, err := net.Listen("tcp", "0.0.0.0:9090")
    	if err != nil {
    		fmt.Printf("listen fail, err: %v
    ", err)
    		return
    	}
    
    	//2.accept client request
    	//3.create goroutine for each request
    	for {
    		conn, err := listener.Accept()
    		if err != nil {
    			fmt.Printf("accept fail, err: %v
    ", err)
    			continue
    		}
    
    		//create goroutine for each connect
    		go process(conn)
    	}
    }
    
    func process(conn net.Conn) {
    	defer conn.Close()
    	for {
    		var buf [128]byte
    		n, err := conn.Read(buf[:])
    
    		if err != nil {
    			fmt.Printf("read from connect failed, err: %v
    ", err)
    			break
    		}
    		str := string(buf[:n])
    		fmt.Printf("receive from client, data: %v
    ", str)
    	}
    }
    

      

    client端

    main.go

    package main
    
    import (
    	"bufio"
    	"fmt"
    	"net"
    	"os"
    	"strings"
    )
    
    func main() {
    	conn, err := net.Dial("tcp", "localhost:9090")
    	defer conn.Close()
    	if err != nil {
    		fmt.Printf("connect failed, err : %v
    ", err.Error())
    		return
    	}
    
    	inputReader := bufio.NewReader(os.Stdin)
    
    	for {
    		input, err := inputReader.ReadString('
    ')
    		if err != nil {
    			fmt.Printf("read from console failed, err: %v
    ", err)
    			break
    		}
    		trimmedInput := strings.TrimSpace(input)
    		if trimmedInput == "Q" {
    			break
    		}
    		_, err = conn.Write([]byte(trimmedInput))
    
    		if err != nil {
    			fmt.Printf("write failed , err : %v
    ", err)
    			break
    		}
    	}
    }
    

      

    分别编译执行服务端和客户端

    客户端通过命令行与服务端简单交互

  • 相关阅读:
    ie6下absolute:fixed问题,完美兼容
    ajax传输 基础一
    获取ip的ip138.com
    css 常用代码解析
    QQ客服出现“企业QQ在线咨询无权限在当前场景使用!” 问题
    用js实现QQ自定义在线图片
    getElement的几中属性介绍
    Ecshop 单选按钮组功能 颜色多选
    IE6完美解决fix问题
    PHP站内搜索、多关键字、加亮显示
  • 原文地址:https://www.cnblogs.com/yin5th/p/9274495.html
Copyright © 2011-2022 走看看