2016-05-24 08:31
浏览 73


I try to make sockets to communicate with my clients.

A socket would be created after some requests to my API. It means, a client connects itself (only by request), but then, he joins a chat, so a socket is created and linked to the good channel.

I already used sockets so I understand how it works (C, C++, C#, Java), but what I want to make, with what I saw on the web, I think it's possible, but I don't understand how to handle it with golang.

I create a first server:

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    r.HandleFunc("/products", ProductsHandler)
    r.HandleFunc("/articles", ArticlesHandler)
    http.Handle("/", r)

But for socket, I need another one?

package main

import "net"
import "fmt"
import "bufio"
import "strings" // only needed below for sample processing

func main() {

    fmt.Println("Launching server...")

    // listen on all interfaces
    ln, _ := net.Listen("tcp", ":8081")

    // accept connection on port
    conn, _ := ln.Accept()   

    // run loop forever (or until ctrl-c)
    for {     
        // will listen for message to process ending in newline (
        message, _ := bufio.NewReader(conn).ReadString('
        // output message received     
        fmt.Print("Message Received:", string(message))
        // sample process for string received     
        newmessage := strings.ToUpper(message)
        // send new string back to client     
        conn.Write([]byte(newmessage + "

Thank for help !

图片转代码服务由CSDN问答提供 功能建议


套接字 会在对我的API提出一些请求后创建。 这意味着,客户端会自己连接(仅通过请求),但是随后,他加入了聊天,因此创建了一个套接字,并将其链接到良好的频道。

我已经使用了套接字,所以我 了解它是如何工作的(C,C ++,C#,Java),但是我想用网上看到的东西来做,我认为这是可能的,但我不知道如何用golang处理它。


  func main(){
r:= mux.NewRouter()
 r.HandleFunc(“ /  “,HomeHandler)
 r.HandleFunc(” / products“,ProductsHandler)
 r.HandleFunc(” / articles“,ArticlesHandler)
 http.Handle(” /“,r)


import“ net” 
import“ fmt” \  nimport“ bufio” 
import“ strings” //仅在下面用于示例处理
func main(){
 fmt.Println(“ Launching server ...”)
 //监听所有内容 interfaces 
 ln,_:= net.Listen(“ tcp”,“:8081”)
 conn,_:= ln.Accept()
结尾的消息,_:= bufio.NewReader(conn).ReadString('  
 newmessage:= strings.ToUpper(message)
 conn.Write([] byte(newmessage +“ 

谢谢 寻求帮助!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题