golang tcp 回显服务器示例

golang代码服务器:

package main
import (
 //"io"
 "log"
 "net"
 "time"
 "fmt"
 "runtime"
)
func main() {
 runtime.GOMAXPROCS(4)//设置cpu个数
 // Listen on TCP port 2000 on all interfaces.
 l, err := net.Listen("tcp", ":2000")
 if err != nil {
  log.Fatal(err)
 }
 defer l.Close()
 for {
  conn, err := l.Accept()
  if err != nil {
   log.Fatal(err)
  }
  // Handle the connection in a new goroutine.
  // The loop then returns to accepting, so that
  // multiple connections may be served concurrently.
  go func(c net.Conn) {
   defer c.Close()
   var buf = make([]byte, 512)
   for {
    cnt, err := c.Read(buf)
    if err != nil {
     fmt.Printf("recv failed : %s", err)
     return
    }
   
    //fmt.Println(string(buf[:cnt]))
    time.Sleep(10)
    _, err = c.Write(buf[:cnt])
    if err != nil {
     fmt.Printf("write failed : %s", err)
     return
    }
   }
  }(conn)
 }
}


客户端python代码:

import threading
import sys
import time
import socket, sys
import select

def echo():
    host = "172.16.2.18"
    textport = 2000
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        port = int(textport)
    except ValueError:
        port = socket.getservbyname(textport, 'tcp')
    s.connect((host, port))
    while 1:
        select.select([],[],[],0.1)
        data = time.ctime()
        data.join("\r\n")
        s.sendall(data)
        #print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
        buf = s.recv(2048)
    

if __name__ == "__main__":
    threads = []
    for i in xrange(3000):
        os = threading.Thread(None,echo)
        os.start()
        threads.append(os)
    
    for x in threads:
        x.join()


你可能感兴趣的:(python,golang)