douyan2680
2016-05-24 08:31
浏览 73
已采纳

Golang-同时使用API​​服务器和Socket

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)
} 
   
 
 

但是对于套接字,我需要另一个吗?

 包main 
 
import“ net” 
import“ fmt” \  nimport“ bufio” 
import“ strings” //仅在下面用于示例处理
 
func main(){
 
 fmt.Println(“ Launching server ...”)
 
 //监听所有内容 interfaces 
 ln,_:= net.Listen(“ tcp”,“:8081”)
 
 //接受端口上的连接
 conn,_:= ln.Accept()
 
  //永远运行循环(或直到ctrl-c)
 {{
 //将监听消息以换行符(
)
结尾的消息,_:= bufio.NewReader(conn).ReadString('  
')
 //接收到输出消息
 fmt.Print(“接收到消息:”,字符串(消息))
 //接收到字符串的示例过程
 newmessage:= strings.ToUpper(message)
  //将新字符串发送回客户端
 conn.Write([] byte(newmessage +“ 
”))
} 
} 
   
 
 

谢谢 寻求帮助!

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

2条回答 默认 最新

相关推荐 更多相似问题