PHP的SOCKET

Rain_Z001 2001-08-23 06:20:47
加精
没办法,没找到太好的文章!
LXXXII. Socket functions

Warning
This module is EXPERIMENTAL. That means, that the behaviour of these functions, these function names, in concreto ANYTHING documented here can change in a future release of PHP WITHOUT NOTICE. Be warned, and use this module at your own risk.


The socket extension implements a low-level interface to the socket communication functions, providing the possibility to act as a socket server as well as a client.

The socket functions described here are part of an extension to PHP which must be enabled at compile time by giving the --enable-sockets option to configure.

For a more generic client-side socket interface, see fsockopen() and pfsockopen().

When using these functions, it is important to remember that while many of them have identical names to their C counterparts, they often have different declarations. Please be sure to read the descriptions to avoid confusion.

That said, those unfamiliar with socket programming can still find a lot of useful material in the appropriate Unix man pages, and there is a great deal of tutorial information on socket programming in C on the web, much of which can be applied, with slight modifications, to socket programming in PHP.

Example 1. Socket example: Simple TCP/IP server

This example shows a simple talkback server. Change the address and port variables to suit your setup and execute. You may then connect to the server with a command similar to: telnet 192.168.1.53 10000 (where the address and port match your setup). Anything you type will then be output on the server side, and echoed back to you. To disconnect, enter 'quit'.

<?php
error_reporting (E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit (0);

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
echo "socket() failed: reason: " . strerror ($sock) . "\n";
}

if (($ret = bind ($sock, $address, $port)) < 0) {
echo "bind() failed: reason: " . strerror ($ret) . "\n";
}

if (($ret = listen ($sock, 5)) < 0) {
echo "listen() failed: reason: " . strerror ($ret) . "\n";
}

do {
if (($msgsock = accept_connect($sock)) < 0) {
echo "accept_connect() failed: reason: " . strerror ($msgsock) . "\n";
break;
}
do {
$buf = '';
$ret = read ($msgsock, $buf, 2048);
if ($ret < 0) {
echo "read() failed: reason: " . strerror ($ret) . "\n";
break 2;
}
if ($ret == 0) {
break 2;
}
$buf = trim ($buf);
if ($buf == 'quit') {
close ($msgsock);
break 2;
}
$talkback = "PHP: You said '$buf'.\n";
write ($msgsock, $talkback, strlen ($talkback));
echo "$buf\n";
} while (true);
close ($msgsock);
} while (true);

close ($sock);
?>





Example 2. Socket example: Simple TCP/IP client

This example shows a simple, one-shot HTTP client. It simply connects to a page, submits a HEAD request, echoes the reply, and exits.

<?php
error_reporting (E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = getservbyname ('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname ('www.php.net');

/* Create a TCP/IP socket. */
$socket = socket (AF_INET, SOCK_STREAM, 0);
if ($socket < 0) {
echo "socket() failed: reason: " . strerror ($socket) . "\n";
} else {
"socket() successful: " . strerror ($socket) . "\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = connect ($socket, $address, $service_port);
if ($result < 0) {
echo "connect() failed.\nReason: ($result) " . strerror($result) . "\n";
} else {
echo "OK.\n";
}

$in = "HEAD / HTTP/1.0\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
write ($socket, $in, strlen ($in));
echo "OK.\n";

echo "Reading response:\n\n";
while (read ($socket, $out, 2048)) {
echo $out;
}

echo "Closing socket...";
close ($socket);
echo "OK.\n\n";
?>





Table of Contents
accept_connect — Accepts a connection on a socket
bind — Binds a name to a socket
close — Closes a file descriptor
connect — Initiates a connection on a socket
listen — Listens for a connection on a socket
read — Read from a socket
socket — Create a socket (endpoint for communication)
strerror — Return a string describing a socket error
write — Write to a socket
User Contributed Notes
Socket functions


paulwade@greenbush.com
12-Nov-2000 11:55

[Editor's note: Not completely correct. Look at the (still not documented) functions (from the PHP source code):


int gethostbyaddr(string addr, string &name)
Given a human-readable address, sets name to be the host's name
int gethostbyname(string name, string &addr)
Given a hostname, sets addr to be a human-readable version of the host's address
int getpeername(int fd, string &addr[, int &port])
Given an fd, stores a string representing sa.sin_addr and the value of sa.sin_port into addr and port describing the remote side of a socket
int getsockname(int fd, string &addr[, int &port])
Given an fd, stores a string representing sa.sin_addr and the value of sa.sin_port into addr and port describing the local side of a socket

These and other functions will be documented here eventually]

I filed a wishlist bug because I do not see any way to get the IP address of the client. Until this is added I would use caution in implementing servers with PHP4. You can control access to selected ports at the OS level with linux. It might be wise to limit port access to specific machines or subnets.


tom.anheyer@berlinonline.de
09-Feb-2001 03:49

There are many undocumentated functions yet:

resource fd_alloc(void)
Allocates a file descriptor set

bool fd_dealloc(void)
De-allocates a file descriptor set

bool fd_set(int fd, resource set)
Adds a file descriptor to a set

bool fd_clear(int fd, resource set)
Clears a file descriptor from a set

bool fd_isset(int fd, resource set)
Checks to see if a file descriptor is set within the file descrirptor set

void fd_zero(resource set)
Clears a file descriptor set

int select(int max_fd, resource readfds, resource writefds, resource exceptfds, int tv_sec, int tv_usec)
Runs the select() system call on the sets mentioned with a timeout specified by tv_sec and tv_usec

int open_listen_sock(int port)
Opens a socket on port to accept connections

bool set_nonblock(int fd)
Sets nonblocking mode for file descriptor fd

int getsockname(int fd, string &addr[, int &port])
Given an fd, stores a string representing sa.sin_addr and the value of sa.sin_port into addr and port describing the local side of a socket

int gethostbyname(string name, string &addr)
Given a hostname, sets addr to be a human-readable version of the host's address

int getpeername(int fd, string &addr[, int &port])
Given an fd, stores a string representing sa.sin_addr and the value of sa.sin_port into addr and port describing the remote side of a socket

int gethostbyaddr(string addr, string &name)
Given a human-readable address, sets name to be the host's name

resource build_iovec(int num_vectors [, int ...])
Builds a 'struct iovec' for use with sendmsg, recvmsg, writev, and readv
First parameter is number of vectors, each additional parameter is the
length of the vector to create.

string fetch_iovec(resource iovec_id, int iovec_position)
Returns the data held in the iovec specified by iovec_id[iovec_position]

bool set_iovec(resource iovec_id, int iovec_position, string new_val)
Sets the data held in iovec_id[iovec_position] to new_val

bool add_iovec(resource iovec_id, int iov_len)
Adds a new vector to the scatter/gather array

bool delete_iovec(resource iovec_id, int iov_pos)
Deletes a vector from an array of vectors

bool free_iovec(resource iovec_id)
Frees the iovec specified by iovec_id

int readv(int fd, resource iovec_id)
Reads from an fd, using the scatter-gather array defined by iovec_id

int writev(int fd, resource iovec_id)
Writes to a file descriptor, fd, using the scatter-gather array defined by iovec_id

int recv(int fd, string buf, int len, int flags)
Receives data from a connected socket
May be used with SOCK_DGRAM sockets.

int send(int fd, string buf, int len, int flags)
Sends data to a connected socket
May be used with SOCK_DGRAM sockets.

int recvfrom(int fd, string &buf, int len, int flags, string &name [, int &port])
Receives data from a socket, connected or not

int sendto(int fd, string buf, int len, int flags, string addr [, int port])
Sends a message to a socket, whether it is connected or not

int recvmsg(int fd, resource iovec, array &control, int &controllen, int &flags, string &addr [, int &port])
Used to receive messages on a socket, whether connection-oriented or not

int sendmsg(int fd, resource iovec, int flags, string addr [, int port])
Sends a message to a socket, regardless of whether it is connection-oriented or not

int getsockopt(int fd, int level, int optname, array|int &optval)
Gets socket options for the socket
If optname is SO_LINGER, optval is returned as an array with members
"l_onoff" and "l_linger", otherwise it is an integer.

int setsockopt(int fd, int level, int optname, int|array optval)
Sets socket options for the socket
If optname is SO_LINGER, optval is expected to be an array
with members "l_onoff" and "l_linger", otherwise it should be an integer.

int socketpair(int domain, int type, int protocol, array &fds)
Creates a pair of indistinguishable sockets and stores them in fds.

int shutdown(int fd, int how)
Shuts down a socket for receiving, sending, or both.


11-Apr-2001 04:31

i've tested the 'one-shot http client' with some sites (yahoo, google, etc) and always had the same problem: read() won't return 0 when finished, rather a negative number. thus the read line would be

while (read ($socket, $out, 2048) >= 0)

this happens with php 4.0.4pl1.


nospam@1111-internet.com
20-Apr-2001 04:05

I also had some difficulties getting my http client to work properly when it came to reading response data from the socket (I'm using PHP 4.0.4pl1). The <=0 return value from the "read" call was only part of the problem.

I managed to get it working as follows:

<?php

function get_web_page ($url)
{

// ...
// main part of http client
// ...

/*
// this didn't work
$read="";
while (read($socket, $read_segment, 2048)>0)
{
$read.=$read_segment;
// test - even this didn't work
echo $read_segment;
// test 2 - this actually did work, but it's relatively useless
echo "1234 $read_segment";
}
close ($socket);
return $read;
*/

// this seems to work reliably
while (read($socket, $read_array[], 2048)>0) {}
close ($socket);
return implode("", $read_array);
}

?>

The scalar $read_segment method was logically sound, but it failed in some odd ways. Something to do with the "&buffer" concept perhaps (see the "read" function page)? I couldn't find any documentation that explains the difference between "&buffer" behavior vs. normal string variable behavior...


martinREMOVE@humany.REMOVE.com
09-May-2001 06:43

Socket support isn't available on windows yet :-( Hopefully soon tho


judeman@yahoo.com
04-Jun-2001 10:49

After several hours of working with sockets in an attempt to do UDP broadcasting, I thought a little help was in order for anyone else looking to do something similar, since it uses a number of those "undocumented" functions. Here's how I did it:

<?php
// here is a basic opening of the a socket. AF_INET specifies the internet domain. SOCK_DGRAM
// specifies the Datagram socket type the 0 specifies that I want to use the default protcol (which in this
// case is UDP)
$sock = socket(AF_INET, SOCK_DGRAM, 0);

// if the file handle assigned to socket is less than 0 then opening the socket failed
if($sock < 0)
{
echo "socket() failed, error: " . strerror($sock) . "\n";
}

// here's where I set the socket options, this is essential to allow broadcasting. An earlier comment (as of
// June 4th, 2001) explains what the parameters are. For my purposes (UDP broadcasting) I need to set
// the broadcast option at the socket level to true. In C, this done using SOL_SOCKET as the level param
// (2) and SO_BROADCAST as the type param (3). These may exist in PHP but I couldn't reference them
// so I used the values that referencing these variables in C returns (namely 1 and 6 respectively). This
// function is basically just a wrapper to the C function so check out the C documentation for more info
$opt_ret = setsockopt($sock, 1, 6, TRUE);

// if the return value is less than one, an error occured setting the options
if($opt_ret < 0)
{
echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
}

// finally I am ready to broad cast something. The sendto function allows this without any
// connections (essential for broadcasting). So, this function sends the contents of $broadcast_string to the
// general broadcast address (255.255.255.255) on port 4096. The 0 (param 4) specifies no special
// options, you can read about the options with man sendto
$send_ret = sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', 4096);

// if the return value is less than 0, an error has occured
if($send_ret < 0)
{
echo "sendto() failed, error: " . strerror($send_ret) . "
\n"; }
// be sure to close your socket when you're done
close($sock);


aaron.cameron@cityvu.com
12-Jun-2001 05:36

I was wondering if anyone has had any trouble setting up a simple listening server in php-4.0.5 running on linux. I have almost exactly the example, none of the commands report errors and the accept_connect() blocks the system as if it were listening, but it refuses to actually accept connects. A quick netstat also shows that it is not in fact listening. I've tried several ports (all above 1024) and the result stays the same.

My only theory is that php4 can't use sockets when it's compiled as a CGI. Any help would be great.


james@introverted.com
13-Jun-2001 12:50

I you are using PHP 4.0.7-dev from CVS then you will find that all of the Sockets module functions have changed. I've put a list together that details the functions and what their arguments are (as of June 12th 2001), as well as a re-written Example 1 from the PHP sockets documentation page (It works!): http://www.php.net/manual/en/ref.sockets.php
The new functions listing and converted Example 1 is available here: http://introverted.com/php-sockets.html



aaron.cameron@cityvu.com
13-Jun-2001 02:42

I've discovered why the server wasn't working. It is actually kind of querky. The ip and port to listen on are read in by a config file reader, and even though the values are trimed, the port wasn't being typcasted to int by bind the way it would in many other functions. By adding an explicit typecast to int in the bind call, everything worked fine.


rumblepipe@altavista.com
28-Jun-2001 12:04

The php socket read() function takes a fourth argument if you expect to use it like you would with c.
The fourth argument I've been using (with success, finally) is PHP_SYSTEM_READ.
I had to get that info from a person associated with this site (thank you), so I'm a little surprised a note about this wasn't already here.

...全文
1159 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
dogun 2002-01-11
  • 打赏
  • 举报
回复
好东西
saving.....
zxyufan 2001-08-23
  • 打赏
  • 举报
回复
收藏~~!收藏~~!收藏~~!
Rain_Z001 2001-08-23
  • 打赏
  • 举报
回复
作者:limodou

  在作者所申请的几个PHP 主页空间中,能够提供mail功能的实在不多,总是调用完mail()函数之后就毫无下文了。但是电子邮件在网上生活中的作用越来越大。想一想网虫上网不收邮件能叫真正的网虫吗?邮件的作用我不想再说了,但是如果主页空间不支持mail()发送那么怎么办呢?我也想过通过socket来实现邮件发送,但无奈对用php 进行socket编程不熟悉,再加上发送邮件要用到SMTP协议,又要读不少的英文了,所以一直也没有去研究过。终于有一天我发现了一篇文章,关于用socket编程发送邮件。我如获至宝般将其拷贝下来,并且将其改造成了一个php 可用的类,供大家使用。原来的文章只是一个简单的例子,而且还有一些错误,在我经过多次的实验、改造终于将其改成了一个直接使用socket,向指定的邮箱发送邮件的类,如果大家和前面关于发送MIME的文章结合起来,就可以实现在不支持mail()函数的网站上发送邮件了。因为发送邮件的过程需要时间,可能与mail()的处理机制还不完全一样,所以速度要慢一些,但是可以解决需要发送邮件功能的燃眉之急,同时你也可以学习用php 进行socket编程。下面就将这个类的实现原理介绍给大家,
同时向大家讲解一些关于SMTP的基本知识。

Socket编程介绍
  向大家申明,本人不是一个TCP/IP编程专家,故在此只是讲出了我的一点理解和体会。

  使用fsockopen函数打开一个Internet连接,函数语法格式:

int fsockopen(string hostname, int port, int [errno], string [errstr], int [timeout]);

  参数的意思我想不用讲了,这里由于要使用SMTP协议,所以端口号为25。在打开连接成功后,会返回一个socket句柄,使用它就可以象使用文件句柄一样的。可使用的操作有fputs(),fgets(),feof(),fclose() 等。

  很简单地介绍就到这里吧。

SMTP的基础
  基于TCP/IP的因特网协议一般的命令格式都是通过请求/ 应答方式实现的,采用的都是文本信息,所以处理起来要容易一些。SMTP是简单邮件传输协议的简称,它可以实现客户端向服务器发送邮件的功能。所以下面所讲的命令是指客户端向服务器发出请求指令,而响应则是指服务器返回给客户端的信息。

  SMTP分为命令头和信息体两部分。命令头主要完成客户端与服务器的连接,验证等。整个过程由多条命令组成。每个命令发到服务器后,由服务器给出响应信息,一般为3 位数字的响应码和响应文本。不同的服务器返回的响应码是遵守协议的,但是响应正文本则不必。每个命令及响应的最后都有一个回车符,这样使用fputs()和fgets()就可以进行命令与响应的处理了。SMTP的命令及响应信息都是单行的。信息体则是邮件的正文部分,最后的结束行应以单独的"."作为结束行。

  客户端一些常用的SMTP指令为:

HELO hostname: 与服务器打招呼并告知客户端使用的机器名字,可以随便填写
MAIL FROM: sender_id : 告诉服务器发信人的地址
RCPT TO: receiver_id : 告诉服务器收信人的地址
DATA : 下面开始传输信件内容,且最后要以只含有.的特殊行结束
RESET: 取消刚才的指令,从新开始
VERIFY userid: 校验帐号是否存在(此指令为可选指令,服务器可能不支持)
QUIT : 退出连接,结束
  服务器返回的响应信息为(格式为:响应码+空格+解释):

220 服务就绪(在socket连接成功时,会返回此信息)
221 正在处理
250 请求邮件动作正确,完成(HELO,MAIL FROM,RCPT TO,QUIT指令执行成功会返回此信息)
354 开始发送数据,结束以 .(DATA指令执行成功会返回此信息,客户端应发送信息)
500 语法错误,命令不能识别
550 命令不能执行,邮箱无效
552 中断处理:用户超出文件空间
  下面给出一个简单的命令头(这是在打开socket之后做的),是我向stmp.263.net发邮件的测试结果:

HELO limodou
250 smtp.263.net
MAIL FROM: chatme@263.net
250 Ok
RCPT TO: chatme@263.net
250 Ok
DATA
354 End data with .
To: chatme@263.net
From: chatme@263.net
Subject: test
From: chatme@263.net
test
.
QUIT
250 Ok: queued as C46411C5097E0

  这就是一些SMTP的简单知识。相关内容可以查阅RFC。

RFC 821定义了收/发电子邮件的相关指令。
RFC 822则制定了邮件內容的格式。
RFC 2045-2048制定了多媒体邮件內容的格式,
RFC 1113, 1422-1424则是讨论如何增进电子邮件的保密性。

send_mail类的实现
  现在开始介绍我所编写的发送邮件类。有了上面的预备知识了,下面就是实现了。

类的成员变量

var $lastmessage; //记录最后返回的响应信息
var $lastact; //最后的动作,字符串形式
var $welcome; //用在HELO后面,欢迎用户
var $debug; //是否显示调试信息
var $smtp; //smtp服务器
var $port; //smtp端口号
var $fp; //socket句柄

  其中,$lastmessage和$lastact用于记录最后一次响应信息及执行的命令,当出错时,用户可以使用它们。为了测试需要,我还定义了$debug变量,当其值为true时,会在运行过程中显示一些执行信息,否则无任何输出。$fp用于保存打开后的socket句柄。

类的构造


--------------------------------------------------------------------------------
function send_mail($smtp, $welcome="", $debug=false)
{
if(empty($smtp)) die("SMTP cannt be NULL!");
$this->smtp=$smtp;
if(empty($welcome))
{
$this->welcome=gethostbyaddr("localhost");
}
else
$this->welcome=$welcome;
$this->debug=$debug;
$this->lastmessage="";
$this->lastact="";
$this->port="25";
}
--------------------------------------------------------------------------------
  这个构造函数主要完成一些初始值的判定及设置。$welcome用于HELO指令中,告诉服务器用户的名字。
HELO指令要求为机器名,但是不用也可以。如果用户没有给出$welcome,则自动查找本地的机器名。

显示调试信息

--------------------------------------------------------------------------------
1 function show_debug($message, $inout)
2 {
3 if ($this->debug)
4 {
5 if($inout=="in") //响应信息
6 {
7 $m='<< ';
8 }
9 else
10 $m='>> ';
11 if(!ereg("\n$", $message))
12 $message .= "<br>";
13 $message=nl2br($message);
14 echo "<font color=#999999>${m}${message}</font>";
15 }
16 }
--------------------------------------------------------------------------------
  这个函数用来显示调试信息。可以在$inout中指定是上传的指令还是返回的响应,如果为上传指令,则使用"out";如果为返回的响应则使用"in"。

第3行,判断是否要输出调试信息。
第5行,判断是否为响应信息,如果是,则在第7行将信息的前面加上"<< "来区别信息;否则在第10行加上
    ">> "来区别上传指令。
第11-12行,判断信息串最后是否为换行符,如不是则加上HTML换行标记。第13行将所以的换行符转成HTML的换行标记。
第14行,输出整条信息,同时将信息颜色置为灰色以示区别。

执行一个命令


--------------------------------------------------------------------------------
1 function do_command($command, $code)
2 {
3 $this->lastact=$command;
4 $this->show_debug($this->lastact, "out");
5 fputs ( $this->fp, $this->lastact );
6 $this->lastmessage = fgets ( $this->fp, 512 );
7 $this->show_debug($this->lastmessage, "in");
8 if(!ereg("^$code", $this->lastmessage))
9 {
10 return false;
11 }
12 else
13 return true;
14 }
--------------------------------------------------------------------------------
  在编写socket处理部分发现,一些命令的处理很相似,如HELO,MAIL FROM,RCPT TO,QUIT,DATA命令,都要求根据是否显示调试信息将相关内容显示出来,同时对于返回的响应码,如果是期望的,则应继续处理,如果不是期望的,则应中断出理。所以为了清晰与简化,专门对这些命令的处理编写了一个通用处理函数。
函数的参数中$code为期望的响应码,如果响应码与之相同则表示处理成功,否则出错。

第3行,记录最后执行命令。
第4行,将上传命令显示出来。
第5行,则使用fputs真正向服务器传换指令。
第6行,从服务器接收响应信息将放在最后响应消息变量中。
第7行,将响应信息显示出来。
第8行,判断响应信息是否期待的,如果是则第13行返回成功(true),否则在第10行返回失败(false)。

  这样,这个函数一方面完成指令及信息的发送显示功能,别一方面对返回的响应判断是否成功。

邮件发送处理

  下面是真正的秘密了,可要看仔细了。:)

--------------------------------------------------------------------------------
1 function send( $to,$from,$subject,$message)
2 {
3
4 //连接服务器
5 $this->lastact="connect";
6
7 $this->show_debug("Connect to SMTP server : ".$this->smtp, "out");
8 $this->fp = fsockopen ( $this->smtp, $this->port );
9 if ( $this->fp )
10 {
11
12 set_socket_blocking( $this->fp, true );
13 $this->lastmessage=fgets($this->fp,512);
14 $this->show_debug($this->lastmessage, "in");
15
16 if (! ereg ( "^220", $this->lastmessage ) )
17 {
18 return false;
19 }
20 else
21 {
22 $this->lastact="HELO " . $this->welcome . "\n";
23 if(!$this->do_command($this->lastact, "250"))
24 {
25 fclose($this->fp);
26 return false;
27 }
28
29 $this->lastact="MAIL FROM: $from" . "\n";
30 if(!$this->do_command($this->lastact, "250"))
31 {
32 fclose($this->fp);
33 return false;
34 }
35
36 $this->lastact="RCPT TO: $to" . "\n";
37 if(!$this->do_command($this->lastact, "250"))
38 {
39 fclose($this->fp);
40 return false;
41 }
42
43 //发送正文
44 $this->lastact="DATA\n";
45 if(!$this->do_command($this->lastact, "354"))
46 {
47 fclose($this->fp);
48 return false;
49 }
50
51 //处理Subject头
52 $head="Subject: $subject\n";
53 if(!empty($subject) && !ereg($head, $message))
54 {
55 $message = $head.$message;
56 }
57
58 //处理From头
59 $head="From: $from\n";
60 if(!empty($from) && !ereg($head, $message))
61 {
62 $message = $head.$message;
63 }
64
65 //处理To头
66 $head="To: $to\n";
67 if(!empty($to) && !ereg($head, $message))
68 {
69 $message = $head.$message;
70 }
71
72 //加上结束串
73 if(!ereg("\n\.\n", $message))
74 $message .= "\n.\n";
75 $this->show_debug($message, "out");
76 fputs($this->fp, $message);
77
78 $this->lastact="QUIT\n";
79 if(!$this->do_command($this->lastact, "250"))
80 {
81 fclose($this->fp);
82 return false;
83 }
84 }
85 return true;
86 }
87 else
88 {
89 $this->show_debug("Connect failed!", "in");
90 return false;
91 }
92 }
--------------------------------------------------------------------------------
  有些意思很清楚的我就不说了。

  这个函数一共有四个参数,分别是$to表示收信人,$from表示发信人,$subject表求邮件主题和$message
表示邮件体。如果处理成功则返回true,失败则返回false。

第8行,连接邮件服务器,如果成功响应码应为220。
第12行,设置阻塞模式,表示信息必须返回才能继续。详细说明看手册吧。
第16行,判断响应码是否为220,如果是,则继续处理,否则出错返回。
第22-27行,处理HELO指令,期望响应码为250。
第29-34行,处理MAIL FROM指令,期望响应码为250。
第36-41行,处理RCPT TO指令,期望响应码为250。
第44-49行,处理DATA指令,期望响应码为354。
第51-76行,生成邮件体,并发送。
第52-56行,如果$subject不为空,则查找邮件体中是否有主题部分,如果没有,则加上主题部分。
第59-63行,如果$from不为空,则查找邮件体中是否有发信人部分,如果没有,则加上发信人部分。
第66-70行,如果$to不为空,则查找邮件体中是否有收信人部分,如果没有,则加上收信人部分。
第73-74行,查找邮件体是否有了结束行,如果没有则加上邮件体的结束行(以"."作为单独的一行的特殊行)。
第76行,发送邮件体。
第78-83行,执行QUIT结否与服务器的连接,期望响应码为250。
第85行,返回处理成功标志(true)。
第81-91行,与服务器连接失败的处理。

  以上为整个send_mail类的实现,应该不是很难的。下面给出一个实例。

邮件发送实例
  先给出一个最简单的实例:
--------------------------------------------------------------------------------
<?
1 include "sendmail.class.php3";
2 $email="Hello, this is a test letter!";
3 $sendmail=new send_mail("smtp.263.net", "limodou", true); //显示调示信息
4 if($sendmail->send("chatme@263.net", "chatme@263.net", "test", $email))
5 {
6 echo "发送成功!<br>";
7 }
8 else
9 {
10 echo "发送失败!<br>";
11 }
?>
--------------------------------------------------------------------------------
第1行,装入send_mail类。
第3行,创建一个类的实例,且设置显示调示信息,如果不想显示,可以
    $sendmail=new send_mail("smtp.263.net");。
第4行,发送邮件。


很简单,不是吗?下面再给合以前的发送MIME邮件的例子,给出一个发送HTML附件的例子。

--------------------------------------------------------------------------------
<?php

include "MIME.class.php3";
//注,在发送MIME邮件一文中,这个类文件名为MIME.class,在此处我改成这样的

$to = 'chatme@263.net'; //改为收信人的邮箱
$str = "Newsletter for ".date('M Y', time());

//信息被我改少了
$html_data = '<html><head><title>'. $str. '</title></head>
<body bgcolor="#ffffff">
Hello! This is a test!
</body>
</html>';

//生成MIME类实例
$mime = new MIME_mail("chatme@263.net", $to, $str);

//添加HTML附件
$mime->attach($html_data, "", HTML, BASE64);

//注释掉,采用我的发送邮件处理
//$mime->send_mail();

//生成邮件
$mime->gen_email();

//显示邮件信息
//echo $mime->email."<br>";

//包含sendmail文件
include "sendmail.class.php3";

//创建实例
$sendmail=new send_mail("smtp.263.net", "limodou", true);

//发送邮件
$sendmail->send("chatme@263.net", "chatme@263.net", $str, $mime->email);

?>
--------------------------------------------------------------------------------
  注释写的很清楚,就不再做更多的解释了。如果实际应用中,请将send_mail构造函数中的debug设为
false或不写即可。在此处可以下载关于本文的例子。2000082201.zip }
Rain_Z001 2001-08-23
  • 打赏
  • 举报
回复
下面有些问答还是不错的

Matching Entries

Is it possible for a program to bind to a socket when that socket is already bound to another application to monitor i/o? (100% match) User Rating: (80%)
Is it possible for a program to bind to a socket when that socket is already bound to another application to monitor i/o? Oleg Broytmann, Warren Postma It is impossible. But, why not write a Python program to be a server on port 25, which just opens another port and relays the data. Then reconfigure your original server (say SMTP) to go somewhere else, like 8881, and your Python program can redirect (with a small delay) as well as dumping out what comes in? You can't leave your server app on the port and let anyone else use it, but you can fake it with a relay+dumping program. You could also ...

How do I handle asynchronous file and socket I/O in a Tk-based graphical user interface? (51% match) User Rating: (88%)
How do I handle asynchronous file and socket I/O in a Tk-based graphical user interface? Can I combine a "select" call on some of my file objects with the Tkinter event loop? Grant Edwards, Russell E. Owen Tk file handlers To handle asynchronous reading and writing of files and sockets in a Tk GUI, Tk offers file handlers. The following is my attempt to document them thoroughly. This is based on information from Grant Edwards, who first taught me about them, my own tests and reading about Tk. I have not yet looked at the tkinter code, and that would probably be educational. The subroutine ...

How would I check to see if an object is an instance of a socket? (50% match) User Rating: (100%)
How would I check to see if an object is an instance of a socket? Moshe Zadka, Jerome Chan Use the type() function: >>> type(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) <type 'socket'> In the socket documentation: if type(s)==socket.SocketType: print "hello"

is there a way to connect ColdFusion to a Socket, e.g. to read real-time data (50% match) User Rating: (100%)
is there a way to connect ColdFusion to a Socket, e.g. to read real-time data I'm not 100% sure, but Cold Fusion is not really a real time scripting engine. You could do CFHTTP to an arbitary port at an interval. Once you have the CF script setup you could then use the CF Administrator to schedule it, etc or just run it from some other trigger. A more real time way to do it would be to write a custom VB or C++ object that sits in the background, maybe run from a service, and sucks the data from the port and buffers it to disk/memory and then use CF script CFOBJECT to open a connection to the object ...

How can I stop MySQL from listening on a TCP socket? (50% match) User Rating: (100%)
How can I stop MySQL from listening on a TCP socket? Benjamin Pflugmann To disable the TCP socket (usually port 3306), start the server with --skip-networking.

Can I change the default socket that PHP uses for MySQL? (50% match) User Rating: (100%)
Can I change the default socket that PHP uses for MySQL? Jim Winstead Code to do this will appear in 3.0.10. It allows a syntax like: mysql_connect("localhost:/bfd/msql.sock", ...

Cannot connect through socket '/tmp/mysql.sock' (49% match) User Rating: (75%)
Cannot connect through socket '/tmp/mysql.sock' See the following entries which should help answer this problem: http://www.faqts.com/knowledge-base/view.phtml/aid/1786/fid/10/lang/en http://www.faqts.com/knowledge-base/view.phtml/aid/444/fid/13/lang/en

Threading and timeouts (5% match) User Rating: (100%)
Threading and timeouts Hans Nowak, Snippet 331, Phil Mayes """ Packages: networking.sockets """ """ >Are timeouts possible inside threads? > >Eg: escaping from an attempt to use smtplib.SMTP().sendmail() inside a >child thread if the remote host is being extremely slow. > >It doesn't seem possible to use the traditional signal(SIG_ALRM,...) >approach because signals only work inside the main thread. > >The only option I can think of is to re-write the smtplib module to use >`select', but does anyone know of a simpler solution ...

I keep getting an ERROR 2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' It dissapeared from /tmp. (2% match) User Rating: (81%)
I keep getting an ERROR 2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' It dissapeared from /tmp. There are two reasons why this could happen. The one is that the mysql demon is down. The other is that you try to use a socket that the demon is not expecting. I had this problem using php on a Suse linux system. If THIS is the case and you have root access to the low traffic mysql server, shut it down, use the mysql command at the prompt and see by the error message which socket the client normally uses. You should edit your php.ini file. There is an entry mysql default ...

Catching signals/alarm (was: Problems with signals & exceptions...) (1% match) User Rating: (100%)
... Python 1.5.2 that came with FreeBSD 3.2 (well, on disk 1 of | the <n>-disk set). The following program works properly under Red Hat | Linux version 6.0 running a self-compiled Python 1.5.2 (in place of the | 1.5.1 which comes with Red Hat 6.0, which does not properly handle | signals during socket i/o calls). How it works: it listens to port 6664. | When it gets a connection, it then sets an alarm handler and alarm and | then tries to read from the socket. If it does not get data within 10 | seconds, it then times out, at which point the alarm handler throws an | exception and aborts the ...

Rudimentary dict (RFC 2229) client library (1% match) User Rating: (100%)
Rudimentary dict (RFC 2229) client library Hans Nowak, Snippet 377, Jim Meier """ Packages: networking.sockets;basic_datatypes.dictionaries """ """ I needed to use some dict servers and wanted to do it in python. """ # -----> dictlib.py (cut here to end of message) <----------- import socket import types import re import string class DictDefinition: def __init__(self, dict, word): self.dict = dict self.word = word self.defs = {} def definitions(self): return self.defs.values() def adddef(self, dictid, definition): self.defs[dictid ...

whois client (1% match) User Rating: (50%)
... , Chunk Light Fluffy """ Packages: networking.internet """ """ > Is there any module that implement all of part of the whois tool ? Whois clients are very simple minded. All the real work is done by the server, so all you really have to do is open the socket, send a one line query, then read the response until the server closes the socket. If you want something smarter, or even just a decent list of all the whois servers, try <URL:http://www.geektools.com/software.html> """ import socket, string WHOIS_PORT = 43 CRLF = "\015 ...

How can I free a port that has been used by a python server? (1% match) User Rating: (100%)
... == '__main__': port = 1729 # Called from interactive session, debug mode. proxy = Server (('127.0.0.1', port), Handler) proxy.serve_forever () ###################################################################### The problem is, when I run this more than once in interactive mode, I get the error: socket.error: (98, 'Address already in use') Is there some way to free up port 1729 when proxy gets destroyed? Solution: Normally you should close the socket properly before exiting. You could try to catch KeyboardInterrupt or whatever signal you use to break out of serve_forever(), but it's problematic ...

Telnet client for Win32 (1% match) User Rating: (100%)
... Linux console... > I don't want to use the M$ telnet client :( Okay. Win32/text based... I assume you're after a non-line buffered input. Try this. It's not quite right, but you can fiddle... """ # Dodgy telnet client for win32 # Portions of code snipped from Python-1.5.2/Demo/sockets/telnet.py import msvcrt, socket, select, sys IAC = chr(255) # Interpret as command DONT = chr(254) DO = chr(253) WONT = chr(252) WILL = chr(251) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect("myhost", 23) iac = 0 opt = "" while 1: rl, wl, xl = [s],[],[] rl, ...

Why I get this Warning: MySQL Connection Failed: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'(111) /path/a.php3 (1% match) User Rating: (43%)
Why I get this Warning: MySQL Connection Failed: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'(111) /path/a.php3 http://www.php.net/manual/function.mysql-pconnect.php Are you 100% sure your mysql server is running on your local box? Are you sure your are using the right port? If it's none of these then it could be that the mysql.sock file is in a non-standard place on the machine (on a server I recently used it was in /tmp/mysql.sock). To get over this find out where it is (find / - name "mysql.sock" -type f) and then pass this in the (p)connect function ...

Resuming with ftplib/httplib? (1% match) User Rating: (100%)
... ntransfercmd(self, cmd, resume): '''Initiate a transfer over the data connection. If the transfer is active, send a port command and the transfer command, and accept the connection. If the server is passive, send a pasv command, connect to it, and start the transfer command. Either way, return the socket for the connection and the expected size of the transfer. The expected size may be None if it could not be determined.''' size = None if self.passiveserver: host, port = parse227(self.sendcmd('PASV')) conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn.connect(host, port) if resume: ...

How do I format my request to get an url/socket when there is a proxy in themiddle? (1% match) User Rating: (92%)
How do I format my request to get an url/socket when there is a proxy in themiddle? David Fisher urllib has proxy support built-in, but not documented. >>> import urllib >>> proxy = { 'http': r' http://192.168.1.1:3128'} #squid proxy on my local network >>> u = urllib.URLopener(proxies = proxy) >>> f = u.open(r' http://www.python.org') >>> print f.read() <HTML> <!-- THIS PAGE IS AUTOMATICALLY GENERATED. DO NOT EDIT. --> <!-- Mon Feb 28 11:00:24 2000 --> <!-- USING HT2HTML 1.1 --> <!-- SEE http://www.python.org/~bwarsaw/software ...

How can I store a picture in MySQL? (1% match) User Rating: (87%)
... better at caching and retrieving files for web use than mySQL is, or will ever need to be (well unless you can prove me wrong :). Consider the two senarious: to show db images: - the image is first read from the data file into MySQL record buffer - from the record buffer the image goes into the socket - the application reads it from the socket into its internal buffer - the contents of the internal buffer are forwarded to the user file system, not even super highly optimized: - the image is read from the data file into internal buffer of the web server. - the contents of the internal buffer are ...

I'm using a LAMP setup with a Flash interface. How do I set up a chat using PHP that updates all the browsers viewing the chat page? (1% match) User Rating: (88%)
... . How do I set up a chat using PHP that updates all the browsers viewing the chat page? http://www.aralbalkan.com/050301/how/ The best way to set up a chat / multi-user game with Flash is to use a java servlet that will broadcast to all connected broswers running the movie. You can use an XML Socket connection and a XML socket server like the Fortress Server (http://www.xadra.com/) I've got a very simple example of how what you're trying to do can be achieved *without* using a socket server. It is a simple prototype for a system what would allow synchronized Flash presentations running on different ...

What should be used to pass encrypted data back and forth? (1% match) User Rating: (33%)
What should be used to pass encrypted data back and forth? How to post data to port 443 (SSL) with PHP socket ? Sascha Schumann http://www.php.net/manual/ref.mcrypt.php3 The mcrypt functions spit out binary data, you can run them through bin2hex() to convert them to an ASCII representation. http://www.php.net/manual/function.bin2hex.php3 Alternatively, if you simply want to pass them through URLs, you may need to urlencode() them first. http://www.php.net/manual/function.urlencode.php3 -- then again, if you mean encrypted as in secure, you should use a SSL (secure sockets layer). Try calling the ...

Fully qualified hostname (1% match) User Rating: (100%)
Fully qualified hostname Hans Nowak, Snippet 137, Jonathan Giddy """ Packages: networking.sockets """ """ >> >What is the best way to get the fully qualified hostname in python (ie >> >hostname.domainname) ? >> > >> >A portable solution would be ideal, but I would settle for Unix only. Under Unix, I get the best (i.e. least surprising) results using the following gethostname function: """ import socket def getdnsnames(name): d = socket.gethostbyaddr(name) names = [ d[0] ] + d[1] + d[2] return names ...

Detecting own computer's IP (1% match) User Rating: (78%)
Detecting own computer's IP How do I go about getting my dynamic IP address? Hans Nowak, Snippet 188, Python Snippet Support Team """ Packages: networking.sockets """ """ detectip.py Detects your own IP address. No big deal on Python; more work on Delphi (where the code originated from :). """ import socket def detectip(): buf = socket.gethostname() remotehost = socket.gethostbyname(buf) return remotehost if __name__ == "__main__": print "Your IP address is", detectip() raw_input()

Detecting own computer's IP (1% match) User Rating: (78%)
Detecting own computer's IP How do I go about getting my dynamic IP address? Hans Nowak, Snippet 188, Python Snippet Support Team """ Packages: networking.sockets """ """ detectip.py Detects your own IP address. No big deal on Python; more work on Delphi (where the code originated from :). """ import socket def detectip(): buf = socket.gethostname() remotehost = socket.gethostbyname(buf) return remotehost if __name__ == "__main__": print "Your IP address is", detectip() raw_input()

How can I setup a monitoring service to check that MySQL is always running? (1% match) User Rating: (83%)
How can I setup a monitoring service to check that MySQL is always running? Tim Bunce mysqld runs on port 3306 by default ( you can change it), and also listens on a Unix socket /tmp/mysqld.sock ( you can change that too). Monitoring mysqld is very easy. You can write a program in C or Perl that runs from a cron or as a daemon, periodically connects to MySQL and runs a simple query. If one of the steps fails, it e-mails you or your pager -- about 10 lines in Perl ( Tim Bunce will do it in one :-) ), and about 25 in C. From Tim Bunce - I'd probably head in this direction (untested): perl -MDBI ...

Non-file-based web server? (1% match) User Rating: (100%)
... http return code is 404 size optional info forwarded to do function do(info, fout) info is the result of analyse fout the output stream the function must write the content to fout """ import os import sys import string import SocketServer import BaseHTTPServer import urllib import socket class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): info = self.send_head() do(info, self.wfile) def do_HEAD(self): self.send_head(headOnly = 1) def do_POST(self): ctyp = self.headers.getheader('content-type') if ctyp != 'application/x-www-form-urlencoded': print 'POST ...

Converting data to little endian (1% match) User Rating: (67%)
Converting data to little endian Hans Nowak, Snippet 346, Fredrik Lundh """ Packages: maths.bit_twiddling """ """ > > Hi, I was wondering how to get my data to be represented in little > > endian format. I know that I can use the socket functions to convert to > > network byte order (big endian), but I need to convert to little endian > > (not just the host byte order). > > One possibility is to use the NumPy extensions and store your data in a > multiarray object. There is a byteswapped method of the multiarray object ...

How can I set the User-Agent string for the web robot I'm writing? (1% match) User Rating: (67%)
How can I set the User-Agent string for the web robot I'm writing? se@lakenet.no If you open a socket to retrive the pages, you just output: "User-Agent: whatever\n" as one of the request headers. I would use something like "User-Agent: bot_name/bot_version (bot_purpose; your@email)\n" (and try to make the robot honor "robots.txt" and other nice things ;) if you use fopen(" http://... the User-Agent is set somewhere near line 588 in fopen-wrappers.c...

Why is fgets() always adding slashes to the string it returns? (1% match) User Rating: (100%)
Why is fgets() always adding slashes to the string it returns? Jim Winstead For example, if fgets() sees this string in the socket: <a href="http//www.yahoo.com">Yahoo!</a> it returns: <a href=\"http//www.yahoo.com\">Yahoo!</a> You should check your value of magic_quotes_runtime. From http://www.php.net/manual/configuration.php3 If magic_quotes_runtime is enabled, most functions that return data from any sort of external source including databases and text files will have quotes escaped with a backslash.

Can I write PHP code to interact with a DIFFERENT server as if php were a browser? Cookies and all? (1% match) User Rating: (100%)
... server as if php were a browser? Cookies and all? I believe it is possible to create such a script. However, a good bit of work and research would have to be done. Below is a short script to retrieve a webpage. $host = 'www.faqts.com'; $port = 80; $page = '/index.phtml'; $timeout = 30; // Open a socket connection to the host $fp = fsockopen($host, $port, &$err_num, &$err_msg, $timeout); if ($fp) { // Send request for the page fputs($fp, "GET $page HTTP/1.0\r\n"); // Get the response $response = ''; while (!feof($fp)) $response .= fgets($fp, 128); } else { print("ERROR # ...

RFC compliant mimetools... (1% match) User Rating: (100%)
... occur again in the Universe, # so the caller needn't check the data it is packing for the # occurrence of the boundary. # # The boundary contains dots so you have to quote it in the header. _prefix = None def choose_boundary(): global _prefix import time import random if _prefix == None: import socket import os hostid = socket.gethostbyname(socket.gethostname()) try: uid = `os.getuid()` except: uid = '1' try: pid = `os.getpid()` except: pid = '1' _prefix = hostid + '.' + uid + '.' + pid timestamp = '%.3f' % time.time() seed = `random.randint(0, 32767)` return _prefix + '.' + timestamp + '.' + ...

How can I store a picture in MySQL? (1% match) User Rating: (87%)
... better at caching and retrieving files for web use than mySQL is, or will ever need to be (well unless you can prove me wrong :). Consider the two senarious: to show db images: - the image is first read from the data file into MySQL record buffer - from the record buffer the image goes into the socket - the application reads it from the socket into its internal buffer - the contents of the internal buffer are forwarded to the user file system, not even super highly optimized: - the image is read from the data file into internal buffer of the web server. - the contents of the internal buffer are ...

How can I store a picture in MySQL? (1% match) User Rating: (87%)
... better at caching and retrieving files for web use than mySQL is, or will ever need to be (well unless you can prove me wrong :). Consider the two senarious: to show db images: - the image is first read from the data file into MySQL record buffer - from the record buffer the image goes into the socket - the application reads it from the socket into its internal buffer - the contents of the internal buffer are forwarded to the user file system, not even super highly optimized: - the image is read from the data file into internal buffer of the web server. - the contents of the internal buffer are ...

Where can I get an example C program using MySQL? (1% match) User Rating: (62%)
... ); // connect to the mySQL database at localhost mysql_init(&mysql); connection = mysql_real_connect(&mysql, sql_host, /*IP, server name, or localhost, or just NULL for localhost*/ sql_user, /*user name*/ sql_auth, /*password*/ db_name, /*db name*/ 0, /*port number*/ NULL, /*Unix socket name: an addition of 3.23?*/ 0); /*client_flag*/ // check for a connection error if (connection ==NULL) return 0; state = mysql_query(connection, sql_command); if (state!=0) return 0; // must call mysql_store_result() before we can issue any other // query calls result = mysql_store_result(connection); ...

How can I use an external mail server from PHP? (1% match) User Rating: (48%)
How can I use an external mail server from PHP? Jon Parise You can either exec sendmail (or an equivalent) directly, or you can use one of the many PHP SMTP implementions that open an actual socket connection to the remote mail server. Search the archives or examples sites for code.

How do I take an int, which represents an IP address, and convert it back to dotted quad format? (in C, it's inet_ntoa) (1% match) User Rating: (100%)
How do I take an int, which represents an IP address, and convert it back to dotted quad format? (in C, it's inet_ntoa) deja (can't remember *who*, though) def ntoa(long): return string.join(map(str,struct.unpack('4B',struct.pack('<L',long))),'.') In Python 1.6a2 (2.0) it's in the socket module, as inet_ntoa afaik.

Why can't PHP find my mysql.sock file? (1% match) User Rating: (74%)
... making a backup, and recompiling both mysql and php/apache seems to be in order: run ./configure --help to get to see where you can set the sock file for mysql. For recent versions of PHP, you can use "localhost:/path/to/mysql.sock" in your mysql_connect call to tell it where to find the socket.

How can I embed/port Python to Vxworks? (1% match) User Rating: (100%)
... under the control of a "scripting" language. There are three approaches here...embed Python in VxWorks, which is what this note is about, connect Python running on a workstation to the VxWorks shell via telnet, or connect Python on the workstation to a process on the VxWorks box via a socket connection. Which way to go is nice question. The other question one ought to answer is, "why aren't you using rt-linux?". P.P.S. All this code is released under the same terms and conditions as the Python license.

How do I upload a file to an FTP site from my webpage? (1% match) User Rating: (65%)
... approaches to this problem: 1.) If the FTP server is on your domain or webserver, simple upload the file via a form and use the copy command to move it where you want it. There are security issues invoved with doing this. 2.) Write a batch-like script to upload files to your ftp site using the sockets functionality inside of PHP3/4 (source file received via form post) This will take you some time to do, but it can be done. 3.) Use one of the million or so CGI-FTP applications available to upload the file for you (retrieve the file from a form).

How can x threads be started at once and stopped y seconds later, processing only the successfully returned threads? (1% match) User Rating: (100%)
... in y seconds. Solution: You need to use a method of retrieving that recognizes time limits. In your case, you have 3 choices: - a version of urllib where urlopen uses select with a timeout and aborts if the timeout expires (Aahz may have done this?). - a version of urllib that uses non-blocking sockets (then no threads needed). - use separate processes instead of separate threads (because you *can* kill a process and properly release resources). If none of those options are available to you - just ignore the thread if it's too slow.

Is there any way to set a time-out interval when reading URLs? (1% match) User Rating: (44%)
Is there any way to set a time-out interval when reading URLs? Oleg Broytmann Possible ways: use multiprocessing (forking or multithreading); use non-blocking sockets and select(); use asyncore library.

Is it possible to implement timeout on read? (1% match) User Rating: (100%)
... to implement timeout on read? Peter Schneider-Kamp, Gerrit Holl Problem: Is it possible to implement timeout on read? eg. answer = sys.stdin.readline() but I want it to timeout after 30 seconds. Solution: Have a look at the select module. For an example how this can be used for a timeout (but for socket.read()) see: http://www.timo-tasi.org/python/timeoutsocket.py --------- It's not crossplatform, but on Unix, the signal module is your friend. You could use such code: <example> #!/usr/bin/python import signal import sys TIMEOUT = 10 def f(signum, frame): print "Too late!" print ...

Are there any current SSL libraries for Python? (1% match) User Rating: (100%)
... thing. Word on the street is that you should look in the prereleases of python 1.6 (renamed 2.0) for the "right" long-term solution. I've downloaded the CVS and it looks like you will have to uncomment a couple of lines in: python/dist/src/Modules/Setup.in Here is the relevant section: # Socket module compiled with SSL support; you must edit the SSL variable: #SSL=/usr/local/ssl #socket socketmodule.c \ # -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ # -L$(SSL)/lib -lssl -lcrypto # The crypt module is now disabled by default because it breaks builds # on many systems (where ...

Is there a HTML search engine written in Python? (1% match) User Rating: (100%)
... easier to build than a fully dynamic one. An interesting GPL'd indexing package is SWISH++ see: http://www.best.com/~pjl/software/swish/ A good tactic might be to use this for your indexing, and running the search engine as a daemon, building a python interface to talk to it via Unix domain sockets or alternately shelling out and capturing and parsing the return values. You also might want to try using Index Server/ASP combo before going to any third party solution...full text searching is no trivial matter and chances are it'll give you all the tinkering options you could want. Additionally: ...





© 1999-2000 Synop Software
zxyufan 2001-08-23
  • 打赏
  • 举报
回复
e文……//汗~~~~

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧