在PHP和Golang中实现TCP通信是常见的网络编程任务。以下是两种语言实现TCP服务端和客户端的基本方法:

PHP实现TCP通信

PHP通过socket扩展来实现TCP通信。以下是一个简单的TCP服务器端示例:

<?php
$address = '127.0.0.1';
$port = 9999;

// 创建socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($sock, $address, $port);
socket_listen($sock);

while(true) {
    $client = socket_accept($sock);
    $data = socket_read($client, 2048);
    socket_write($client, "Server received: " . $data);
    socket_close($client);
}

socket_close($sock);
?>

客户端示例:

<?php
$address = '127.0.0.1';
$port = 9999;

// 创建socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, $address, $port);

socket_write($sock, "Hello, Server!");
$response = socket_read($sock, 2048);
echo "Server response: ".$response;

socket_close($sock);
?>

Golang实现TCP通信

Golang通过net包来实现TCP通信。以下是一个简单的TCP服务器端示例:

package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
)

func main() {
	listen, err := net.Listen("tcp", "127.0.0.1:9999")
	if err != nil {
		fmt.Println("Listen failed:", err)
		return
	}
	defer listen.Close()
	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("Accept failed:", err)
			continue
		}
		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	defer conn.Close()
	reader := bufio.NewReader(conn)
	for {
		message, err := reader.ReadString('\n')
		if err != nil {
			fmt.Println("Read failed:", err)
			break
		}
		fmt.Println("Client says:", message)
		conn.Write([]byte("Server received: " + message))
	}
}

客户端示例:

package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
)

func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:9999")
	if err != nil {
		fmt.Println("Dial error:", err)
		return
	}
	defer conn.Close()

	fmt.Println("Enter messages (send 'q' to quit):")
	input := bufio.NewReader(os.Stdin)
	for {
		fmt.Print("-> ")
		message, _ := input.ReadString('\n')
		message = strings.TrimSpace(message)
		if message == "q" {
			break
		}
		conn.Write([]byte(message))
		response := make([]byte, 2048)
		n, err := conn.Read(response)
		if err != nil {
			fmt.Println("Read error:", err)
			break
		}
		fmt.Println("Server response:", string(response[:n]))
	}
}

在PHP中,你可以使用socket_create(), socket_bind(), socket_listen(), socket_accept(), socket_read(), 和 socket_write()等函数来创建和处理TCP连接。而在Golang中,你通常会使用net.Listen()来启动一个监听,然后通过Accept()方法接受连接,并使用Read()Write()方法来处理数据。

两种语言各有优势,PHP在Web开发中更为常见,而Golang则以其并发处理能力著称。选择哪种语言取决于你的具体需求和场景。