From d7a1ea0e6baeae0c3282de12d2d88c4a4c68ed7f Mon Sep 17 00:00:00 2001 From: mikespook Date: Wed, 16 Mar 2011 20:34:07 +0800 Subject: [PATCH] Added a socket client, just for test. --- test/Makefile | 17 ++++++++++++ test/client.go | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 test/Makefile create mode 100644 test/client.go diff --git a/test/Makefile b/test/Makefile new file mode 100644 index 0000000..cab8f72 --- /dev/null +++ b/test/Makefile @@ -0,0 +1,17 @@ +# Copyright 2009 The Go Authors. All rights reserved. +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file. + +include $(GOROOT)/src/Make.inc + +TARG=client +GOFILES=\ + client.go\ + +CLEANFILES+=client + +include $(GOROOT)/src/Make.pkg + +%: install %.go + $(GC) $*.go + $(LD) -o $@ $*.$O diff --git a/test/client.go b/test/client.go new file mode 100644 index 0000000..7bc6b91 --- /dev/null +++ b/test/client.go @@ -0,0 +1,74 @@ +package main + +import ( + "net" + "log" + "fmt" +) + +type Client struct { + c * net.TCPConn + w chan []byte + r chan []byte +} + +func NewClient() * Client { + client := new(Client) + wch := make(chan []byte, 2048) + rch := make(chan []byte, 2048) + client.w = wch + client.r = rch + addr, err := net.ResolveTCPAddr("127.0.0.1:4730") + if err != nil { + log.Panic(err.String()) + } + c, err := net.DialTCP("tcp", nil, addr) + client.c = c + if err != nil { + log.Panic(err.String()) + } + go client.ReadLoop() + go client.WriteLoop() + return client +} + +func (client * Client) ReadLoop() { + for { + buf := make([]byte, 2048) + _, err := client.c.Read(buf) + if err != nil { + client.c.Close() + break; + } + client.r <- buf + } +} + +func (client * Client) WriteLoop() { + for { + select { + case buf := <- client.w: + client.c.Write(buf) + } + } +} + +func (client * Client) Write(data []byte) { + client.w <- data +} + +func (client * Client) Read() []byte{ + var buf []byte + select { + case buf = <- client.r: + } + return buf +} + +func main() { + client := NewClient() + client.Write([]byte("TEST\r\n")) + for { + fmt.Println(client.Read()) + } +}