Go语言-使用去程的客户端

前端之家收集整理的这篇文章主要介绍了Go语言-使用去程的客户端前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

以下为客户端代码

服务端请见吕志钊写的《Go语言-使用去程的Echo服务器》http://my.oschina.net/nalan/blog/75626

一样,废话不说了,直接上代码.里面注释应该很清楚了

/**
 * Created with IntelliJ IDEA.
 * User: liaojie
 * Date: 12-9-5
 * Time: 下午2:42
 * To change this template use File | Settings | File Templates.
 */
package main

import (
	//"__PB__/GAME_PB_"
	//"code.google.com/p/goprotobuf/proto"
	"net"
	"fmt"
	"bufio"
	"os"
	//"flag"
	"log"
	"time"
)
var running bool;
var (
	host = "192.168.0.27";
	port = "12346";
	laddr = host + ":" + port;
)

func main() {
	//flag.Parse();
	running = true;

	log.Printf("Starting... ");
	conn,err := net.Dial("tcp",laddr)
	if err != nil { log.Printf("与服务器%s握手失败;\n 错误:%s",host,err); os.Exit(1); }
	defer conn.Close();
	reader := bufio.NewReader(os.Stdin);
	name,_ := reader.ReadBytes('\n');
	conn.Write(name[0:len(name)-1]);
	go client_receiver(conn);
	go client_sender(conn);
	for ;running; {
		time.Sleep(1*1e9);
	}
}

//客户端发送器
func client_sender(conn net.Conn){
	reader := bufio.NewReader(os.Stdin);
	for {
		fmt.Print("Server>")
		input,_ :=reader.ReadBytes('\n')
		if string(input) =="/quit\n"{
			conn.Write([]byte("/quit\n"))
			running = false;
			break;
		}
		conn.Write(input[0:len(input)-1])
	}

}


//客户端接收器
func client_receiver(conn net.Conn){
	//无限循环
	for running {
		fmt.Println("===%s",readabc(conn));
		fmt.Print("You>");
	}
}

//读书连接
func readabc(conn net.Conn) string{
	buf := make([]byte,1024)
	_,err :=conn.Read(buf);
	if err != nil {
//		log.Printf("接收错误:%s",err);
//		defer conn.Close();
		log.Printf("警告!连接已断开: %s \n",err);
		os.Exit(1);
	}
	return string(buf)
}
原文链接:https://www.f2er.com/go/191448.html

猜你在找的Go相关文章