728x90


tcp와 tcp끼리 통신하는건 여러분도 많이 봤을 것이다.

그러나 경우에 따라서... 그럴 경우가 있는지 솔직히 잘모르겠는데

tcp와 http가 통신하는 경우도 있다.

사실 원리적으로는 가능하다.

http역시 tcp로 전달하는 것이기 때문이다.

그럼 경우에 수는 두가지가 있다.


1 - tcp서버 http클라이언트

2 - tcp클라이언트 http서버


여기서 우리는 1번을 할것이다.


server


package main

import (
"io"
"log"
"net"
)

func main() {
l, err := net.Listen("tcp", ":8000")
if nil != err {
log.Println(err);
}
defer l.Close()

for {
conn, err := l.Accept()
if nil != err {
log.Println(err);
continue
}
defer conn.Close()
go ConnHandler(conn)
}
}

func ConnHandler(conn net.Conn) {
recvBuf := make([]byte, 4096)
for {
n, err := conn.Read(recvBuf)
if nil != err {
if io.EOF == err {
log.Println(err);
return
}
log.Println(err);
return
}
if 0 < n {
myResp := `HTTP/1.1 200 OK
Server: nginx
Date: Mon, 07 Sep 2015 10:39:12 GMT
Content-Type: application/json
Content-Length: 332
Connection: close
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

{
"name": "jiharu",
"age": "20000"
}`
log.Println(myResp)
_, err = conn.Write([]byte(myResp))
conn.Close()
if err != nil {
log.Println(err)
return
}
}
}
}

서버로직은 전반적으로 tcp끼리 커넥션 하는것과 별 차이없다.

마짐가에 차이점이라면 데이터를 http형식으로 바꿔준다는 것이다.


          myResp := `HTTP/1.1 200 OK
Server: nginx
Date: Mon, 07 Sep 2015 10:39:12 GMT
Content-Type: application/json
Content-Length: 332
Connection: close
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

{
"name": "jiharu",
"age": "20000"
}`

이 로직은 필자가 귀찮아서 그냥짠 로직인데 여러분의 입맛대로 헤더를 수정해주면된다.


_, err = conn.Write([]byte(myResp))
conn.Close()

또한 마지막에 Close를 반드시 해준다.

http는 연결지향이 아니므로 청크모드나 스트리밍상태가 아니라면 닫아줘야 받았다고 인식하게 된다.


client


package main

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)

func main() {
jsonBody := map[string]interface{}{}
jsonBody["name"] = "kukaro"
jsonBody["age"] = 26
jsonStr, _ := json.Marshal(jsonBody)

resp, _ := http.Post("http://localhost:8000","application/json; charset=UTF-8",bytes.NewBuffer([]byte(jsonStr)))
fmt.Println(resp.Header)
fmt.Println("**********")
fmt.Println(resp)
fmt.Println("**********")
respBody, _ := ioutil.ReadAll(resp.Body)
jsonData := map[string]interface{}{}
json.Unmarshal(respBody, &jsonData)
fmt.Println(jsonData)
}

클라이언트예제인데 go에서 http통신을 보내는 예제는 여기를 참조해라

코드는 별로 특이한건 없다.

요청을 하면 받아서 헤더와 raw데이터, 그리고 json데이터를 뿌려주고 끝난다.



제대로 동작되는지 확인해보자.


+ Recent posts