无法在服务器上运行客户端服务器程序获取错误:socket_bind():无法绑定地址[98]:已在使用的地址

时间:2014-07-06 07:41:39

标签: php sockets

我使用socket创建了一个客户端和服务器程序,它在localhost上工作得很好但是当我通过cpanel将它上传到服务器时它无法正常工作并且它会出现以下错误。最重要的是有时两个程序都在服务器上运行。 我是套接字编程的新手,看过stackoverflow上的一些相关帖子,但无法找到确切的解决方案。

Client: Warning: socket_connect(): unable to connect [111]: Connection refused in .../client.php on line 10
Could not connect to server

Server:Warning: socket_bind(): unable to bind address [98]: Address already in use in ..server.php on line 10
Could not bind to socket

Client.php

<?php
// where is the socket server?
$host    = "XX.XX.XXX.XX";
$port    = 25763;
$message = "Hello Server This is the first message to the server";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server  :".$result;
// close socket
socket_close($socket);
    // print result to browser
?>

Server.php

<?php
// set some variables
$host = "XX.XX.XXX.XX";
$port = 25763;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");

// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : ".$input;
// reverse client input and send back
$output = strrev($input) . "\n";
echo $spawn;
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
// close sockets
socket_close($spawn);
socket_close($socket);
?>

1 个答案:

答案 0 :(得分:2)

对于服务器,您可能希望使用socket_set_opt()在新创建的套接字上设置选项SO_REUSEADDR

有关如何执行此操作的代码,请参阅上面链接的手册页上的示例部分。