服务端用go:(go 1.3)搭建一个tcp服务器,客户端用Delphi。通过socket与go进行通讯:
服务端代码:
package main import ( "fmt" "net" "time" "strings" "net/http" ) func main() { service := ":1200" tcpAddr, err := net.ResolveTCPAddr("tcp4", service) checkError(err) listener, err := net.ListenTCP("tcp", tcpAddr) checkError(err) for { conn, err := listener.Accept() if err != nil { continue } go handleClient(conn) } } func handleClient(conn net.Conn) { request := make([]byte, 1024) defer conn.Close() for { read_len, err := conn.Read(request) if err != nil { fmt.Println(err) break } fmt.Println(read_len) if read_len == 0 { fmt.Println("Notings get!!") break }else{ v_kss:=request[0:read_len]; fmt.Println(string(v_kss)); } } }
客户端代码:
procedure TForm1.btn1Click(Sender: TObject); var sa:TWSAData; wstates:Integer; add:sockaddr_in; begin wstates:=WSAStartup($0202,sa); if wstates<>0 then begin ShowMessage('socket 初始化出错'); exit; end; st:=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP); if st=INVALID_SOCKET then begin ShowMessage('建立socket出错'); WSACleanup; Exit; end; add.sin_family:=PF_INET; add.sin_port:=htons(1200); add.sin_addr.S_addr:=inet_addr(PAnsiChar('127.0.0.1')); wstates:=connect(st,add,SizeOf(add)); if wstates<>0 then begin ShowMessage('连接错误'); WSACleanup; Exit; end; end; procedure TForm1.btn2Click(Sender: TObject); var sendLen :Integer; mdata: TBytes; begin if edt1.Text <> '' then begin mdata:=TEncoding.UTF8.GetBytes(mmo1.Text); //此处要注意下。这么写的话会,传送的字符后面会加上一个回车换行传到服务端。 sendLen := send(st,mdata[0],Length(mdata),0); showmessage(inttostr(sendLen)); if sendLen < 0 then begin ShowMessage('发送出错'); WSACleanup; btn1.Enabled := False; Exit; end; end; end;
有疑问加站长微信联系(非本文作者)