Go에서 간단한 콘솔 채팅을하려고하는데, 연습하기 만하면됩니다. 그러나 서버에서 메시지를 다시 보내는 방법을 모르겠습니다. 서버는 메시지를 수신 한 다음 연결을 닫습니다. 어떻게 응답 할 수 있습니까?Go의 양방향 연결
나는 웹 소켓에 관한 정보를 찾고 있었지만 브라우저와 상호 작용하는 데 사용된다고 생각합니다.
func runServer() {
// Listen on a port
listen, error := net.Listen("tcp", ":8272")
// Handles eventual errors
if error != nil {
fmt.Println(error)
return
}
fmt.Println("Listening in port 8272.")
for {
// Accepts connections
con, error := listen.Accept()
// Handles eventual errors
if error != nil {
fmt.Println(error)
continue
}
fmt.Println("Connection accepted.")
// Handles the connection
go handleConnection(con)
}
}
func handleConnection(con net.Conn) {
fmt.Println("Handling connection.")
var message string
// Decodes the received message
decoder := gob.NewDecoder(con)
error := decoder.Decode(&message)
// Checks for errors
if error != nil {
fmt.Println(error)
} else {
fmt.Println("Received", message)
}
// Closes the connection
con.Close()
fmt.Println("Connection closed.")
}
이 클라이언트의 기능입니다 : 사전에
func runClient() {
// Connects to server
con, error := net.Dial("tcp", "127.0.0.1:8272")
// Handles eventual errors
if error != nil {
fmt.Println(error)
return
}
fmt.Println("Connected to 127.0.0.1:8272.")
// Sends a message
message := "Hello world"
encoder := gob.NewEncoder(con)
error = encoder.Encode(message)
// Checks for errors
if error != nil {
fmt.Println(error)
}
con.Close()
fmt.Println("Message sent. Connection closed.")
}
감사
이 서버의 두 가지 기능입니다.
을)'또는 적어도 당신이 연결을 완료하면 자리로 이동 좋은 시작이 될 것입니다 ... – geoffspear
그러나 응답을 기다리기 위해 어떤 방법을 사용해야합니까? – aochagavia