dsc6517 2017-10-25 15:38
浏览 61
已采纳

TCP聊天应用程序字符串连接错误

I've run into some difficulty when building a simple TCP based chat application in Go. My problem is that after changing the variable name, the formatting seems to go haywire and the text of the message overrides the name of the sender and other characters.

All code snippets below are taken from the server.

type Message struct {
    sender *User
    message string
}

type User struct {
    connection net.Conn
    queue chan string//Simply a queue of messages that will be sent to the client, out of the scope of this question
    name string
}

Code that sets the name: (assuming the command comes in the form "/nick NAME")

command := message.message[1:]
if(strings.HasPrefix(command, "nick")) {
    message.sender.name = command[5:]
    fmt.Println("Set name to: " + message.sender.name)
}

Code that prints the value (note that the error persists if I concatenate the strings using the traditional s1 + s2):

var buffer bytes.Buffer
buffer.WriteString("<")
buffer.WriteString(message.sender.name)
buffer.WriteString("> ")
buffer.WriteString(message.message)
fmt.Println(buffer.String())
sendMessage(buffer.String())

Output (server on left, client on right. Not that I send the message 'Test' both times):

Output

As seen above, the format of the message should have been <NewName123> Test, however the greater than symbol is misplaced and the message test can be seen overriding the name of the user. I'm stumped as to what is causing this problem. The application works as follows: Client connects. Client sends a message, the server reads the message and applies formatting (IE add username in). Server redistributes the message to ALL users (including the sender). The clients display the message.

Any help would be fantastic.

  • 写回答

1条回答 默认 最新

  • douxing8855 2017-10-25 15:56
    关注

    This looks like the name contains a carriage return (), which instructs the terminal to write <NewName123>, then return the carriage (aka. cursor) to the beginning of the line, and then (over)write > Test.

    A strings.TrimSpace(command[5:]) call somewhere should fix this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)