Example #1
0
func main() {

	ConnMap = make(pac.ConnMapType)

	ln, err := pac.Listen("127.0.0.1:8080")

	defer ln.Close()
	pac.CheckError(err)
	fmt.Println("server starting...")

	param := ConnParam

	dbconn, err := DB.Connect(param)
	defer dbconn.Close()
	pac.CheckError(err)

	_, err = dbconn.Execute("USE " + param.DbName)
	pac.CheckError(err)

	for {
		conn, err := ln.AcceptTCP()
		pac.CheckError(err)

		ConnMap[conn.RemoteAddr().String()] = conn

		go handleConnection(conn, dbconn)
	}
}
Example #2
0
func handleConnection(conn *net.TCPConn, dbconn *DB.Connection) {
	defer func() {
		fmt.Println("disconnected :" + conn.RemoteAddr().String())
		conn.Close()
	}()
	fmt.Println("connected:" + conn.RemoteAddr().String())
	info := make([]byte, 512)
	_, err := conn.Read(info)
	pac.CheckError(err)

	fmt.Println(string(info))

	for {
		buf := make([]byte, 512)
		_, err := conn.Read(buf)

		if err != nil {
			return
		}

		data := pac.Decode(buf)

		fmt.Println(data)

		timestamp := strconv.Itoa(int(time.Now().Unix()))

		_, err = dbconn.Execute("INSERT INTO message (fromUserName,toUserName,message,atime) VALUES ('" + data.FromUserName + "','" + data.ToUserName + "','" + data.Message + "'," + timestamp + ")")
		pac.CheckError(err)

		timestr, err := strconv.ParseInt(timestamp, 10, 64)
		var message = time.Unix(timestr, 0).Format("2006-01-02 15:04:05") + " " + data.FromUserName + " 对 " + data.ToUserName + " 说:" + data.Message
		if data.Message != "" {
			pac.Boradcast(string(message+"\n"), ConnMap)
		}

	}
}
Example #3
0
func main() {

	conn, err := pac.Connect("127.0.0.1:8080")
	defer conn.Close()
	pac.CheckError(err)
	fmt.Println("连接成功!\n")

	reader := bufio.NewReader(os.Stdin)
	fmt.Println("你的昵称?")
	fromUserName, _ := reader.ReadString('\n')
	fromUserName = strings.Trim(fromUserName, "\r\n")

	fmt.Println("对方昵称?")

	toUserName, _ := reader.ReadString('\n')
	toUserName = strings.Trim(toUserName, "\r\n")
	conn.Write([]byte("请求" + toUserName))

	fmt.Println("开始与" + toUserName + "聊天")

	go pac.MessageRecived(conn)

	for {

		input, _ := reader.ReadString('\n')
		input = strings.Trim(input, "\r\n")

		var data pac.Data
		data.FromUserName = fromUserName
		data.ToUserName = toUserName
		data.Message = input

		b := pac.Encode(&data)

		if data.Message != "" {
			conn.Write(b.Bytes())
		}

	}

}