アットウィキロゴ

Socket Programming HOWTO

Socket Programming HOWTO
Author: Gordon McMillan

Sockets

Sockets are used nearly everywhere, but are one of the most severely misunderstood technologies around. This is a 10,000 foot overview of sockets. It's not really a tutorial - you'll still have work to do in getting things working. It doesn't cover the fine points (and there are a lot of them), but I hope it will give you enough background to begin using them decently.

ソケットは、ほぼどこでも使用できますが、周りの最も深刻な誤解技術の一つであるされています。
これはソケットの10,000フィートの概要です。
それは本当にチュートリアルではありません - あなたはまだ物事が正常に動作し得ることに実行する作業を必要があります。
それは、細かい点(およびそれらの多くがあります)をカバーしていませんが、
私はそれはあなたにきちんとそれらの使用を開始するのに十分な背景を与えることを願っています。

I'm only going to talk about INET sockets, but they account for at least 99% of the sockets in use. And I’ll only talk about STREAM sockets - unless you really know what you’re doing (in which case this HOWTO isn’t for you!), you’ll get better behavior and performance from a STREAM socket than anything else. I will try to clear up the mystery of what a socket is, as well as some hints on how to work with blocking and non-blocking sockets. But I'll start by talking about blocking sockets. You’ll need to know how they work before dealing with non-blocking sockets.

私はINETソケットについて話をするつもりですが、それらは、使用中のソケットの少なくとも99%を占めています。
と私はストリームソケットについて説明しましょう​​ - あなたが本当に(!このHOWTOがあなたのためではない場合には)
何をやっている知っている限り、あなたは何よりもSTREAMソケットから優れた動作とパフォーマンスを得るでしょう。
私はソケットをブロッキングと非ブロッキングの操作方法でソケットが何かの謎だけでなく、
いくつかのヒントをクリアしようとします。
しかし、私はソケットをブロッキングの話から始めます。
あなたは彼らが非ブロッキングソケットを扱う前に、どのように動作するかを知る必要があります。

Part of the trouble with understanding these things is that “socket” can mean a number of subtly different things, depending on context. So first, let’s make a distinction between a “client” socket - an endpoint of a conversation, and a “server” socket, which is more like a switchboard operator. The client application (your browser, for example) uses “client” sockets exclusively; the web server it’s talking to uses both “server” sockets and “client” sockets.

これらのことを理解する問題の一部は、"ソケット"がコンテキストに応じて、微妙に異なるものの数を意味することができます。
会話のエンドポイント、および交換演算子に似ている"サーバ"ソケット - だから最初は、"クライアント"ソケットの間に区別をしてみましょう。
クライアントアプリケーション(ブラウザ、例えば)は、"クライアント"専用のソケットを使用して、
それがに話しているWebサーバが"サーバ"ソケットと"クライアント"ソケットの両方を使用します。

History

Of the various forms of IPC, sockets are by far the most popular. On any given platform, there are likely to be other forms of IPC that are faster, but for cross-platform communication, sockets are about the only game in town.

IPCの様々な形態の、ソケットがいちばん人気があります。
任意のプラットフォーム上で、高速であるIPCの他の形態がありそうですが、クロスプラットフォームの通信のために、
ソケットは、町で唯一のゲームについてです。

They were invented in Berkeley as part of the BSD flavor of Unix. They spread like wildfire with the Internet. With good reason — the combination of sockets with INET makes talking to arbitrary machines around the world unbelievably easy (at least compared to other schemes).

彼らはバークレーUnixのBSDフレーバーの一環として考案されました。
彼らはインターネットと野火のように広がる。
正当な理由で - INETソケットとの組み合わせは、(少なくとも他のスキームに比べて)信じられないほど簡単に、世界中の任意のマシンに話します。

Creating a Socket

Roughly speaking, when you clicked on the link that brought you to this page, your browser did something like the following:

大雑把に言えば、あなたはこのページにあなたをもたらしたリンクをクリックしたときに、ブラウザは次のようなものでした:

#create an INET, STREAMing socket
s = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)
#now connect to the web server on port 80
# - the normal http port
s.connect(("www.mcmillan-inc.com", 80))

When the connect completes, the sockets can be used to send in a request for the text of the page. The same socket will read the reply, and then be destroyed. That’s right, destroyed. Client sockets are normally only used for one exchange (or a small set of sequential exchanges).

接続が完了すると、ソケットはページのテキストのための要求で送信するために使用することができます。
同じソケットは、応答を読み取り、その後破壊される。そう、破棄されます。
クライアントソケットは通常は1つの交換(またはシーケンシャル·交流の小さなセット)に使用されています。

What happens in the web server is a bit more complex. First, the web server creates a “server socket”:

どのようなウェブ·サーバーで発生すると、少し複雑です。最初に、Webサーバは"サーバソケット"を作成します。

#create an INET, STREAMing socket
serversocket = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)
#bind the socket to a public host,
# and a well-known port
serversocket.bind((socket.gethostname(), 80))
#become a server socket
serversocket.listen(5)

A couple things to notice:
we used socket.gethostname() so that the socket would be visible to the outside world.
If we had used s.bind*1 or s.bind*2 or s.bind*3 we would still have a “server” socket, but one that was only visible within the same machine.

注意すべきいくつかの事:
我々は socket.gethostname() を使うと、ソケットが外の世界に見えるだろうと。
我々は s.bind(('', 80)) または s.bind(('localhost', 80)) または s.bind(('127.0.0.1', 80)) を使用していた場合、
我々はまだ、 "サーバーを持っているでしょう"ソケットが、同じマシン内でのみ表示されていた1。

A second thing to note:
low number ports are usually reserved for ”well known” services (HTTP, SNMP etc).
If you're playing around, use a nice high number (4 digits).

注意2番目のもの:
低い番号のポートは通常、"よく知られている"サービス(HTTP、SNMPなど)用に予約されています。
あなたが遊んでいる場合、素敵な高い番号(4桁)を使用します。

Finally, the argument to listen tells the socket library that we want it to queue up as many as 5 connect requests (the normal max) before refusing outside connections. If the rest of the code is written properly, that should be plenty.

最後に、耳を傾けるの引数は、キューに外部からの接続を拒否する前に5の接続要求(通常最大)のように
多くのそれをしたいソケットライブラリを指示します。
残りのコードが正しく記述されている場合、それは十分でなければなりません。

Now that we have a “server” socket, listening on port 80, we can enter the mainloop of the web server:

今、私たちはポート80でリッスンし、"サーバ"ソケットを持っていることを、我々はWebサーバの[[メイン]]ループを入力することができます。

while 1:
    #accept connections from outside
    (clientsocket, address) = serversocket.accept()
    #now do something with the clientsocket
    #in this case, we'll pretend this is a threaded server
    ct = client_thread(clientsocket)
    ct.run()

There’s actually 3 general ways in which this loop could work - dispatching a thread to handle clientsocket, create a new process to handle clientsocket, or restructure this app to use non-blocking sockets, and mulitplex between our “server” socket and any active clientsockets using select. More about that later. The important thing to understand now is this: this is all a “server” socket does. It doesn’t send any data. It doesn’t receive any data. It just produces “client” sockets. Each clientsocket is created in response to some other “client” socket doing a connect() to the host and port we’re bound to. As soon as we’ve created that clientsocket, we go back to listening for more connections. The two “clients” are free to chat it up - they are using some dynamically allocated port which will be recycled when the conversation ends.

このループが動作可能であった3一般的な方法は実際にある - clientsocketを処理するスレッドをディスパッチすると、
clientsocketを処理するための新しいプロセスを作成するか、このアプリは、非ブロッキングソケットを使用するように再構築し、
当社の"サーバ"ソケットと、任意のアクティブclientsocketsの間で代用する選択を使用します。その詳細は後述。
現在を理解する重要なことはこれです:これはすべての"サーバ"ソケットないことです。
これは、任意のデータを送信しません。これは、任意のデータを受信しません。それだけでは"クライアント"ソケットを生成します。
各clientsocketは、我々はにバインドされているホストとポートに接続を行う他のいくつかの"クライアント"ソケット()に応答して作成されます。
できるだけ早く我々はclientsocketを作成しましたように、我々はより多くの接続を待ち受けるに戻ります。
二人は"クライアント"は、それをチャットして自由である - 彼らは、会話が終了したときにリサイクルされるいくつかの動的に割り当てられたポートを使用しています。

IPC

If you need fast IPC between two processes on one machine, you should look into whatever form of shared memory the platform offers. A simple protocol based around shared memory and locks or semaphores is by far the fastest technique.

1つのマシン上の2つのプロセス間で高速なIPCが必要であれば、プラットフォームが提供する共有メモリのどのような形になっているはずです。
共有メモリとロックやセマフォの周りに基づく単純なプロトコルでは、群を抜いて最速のテクニックです。

If you do decide to use sockets, bind the “server” socket to 'localhost'. On most platforms, this will take a shortcut around a couple of layers of network code and be quite a bit faster.

あなたはソケットを使用することを決定しない場合は、'localhost'に"サーバ"ソケットをバインドします。
ほとんどのプラットフォームで、これはネットワークコードの層のカップルの周りにショートカットを取るとかなり速くなります。

Using a Socket

The first thing to note, is that the web browser’s “client” socket and the web server’s “client” socket are identical beasts. That is, this is a “peer to peer” conversation. Or to put it another way, as the designer, you will have to decide what the rules of etiquette are for a conversation. Normally, the connecting socket starts the conversation, by sending in a request, or perhaps a signon. But that’s a design decision - it’s not a rule of sockets.

最初に注意することは、ウェブブラウザの"クライアント"ソケットとウェブサーバの"クライアント"ソケットが同一の獣であるということです。
つまり、この会話を"ピア·ツー·ピア"である。またはデザイナーとして、あなたはエチケットのルールは会話のためにあるかを決定する必要がありますが、
それは別の言い方をします。通常は、接続ソケットは、おそらくサインオンをリクエストで送信したり、することによって、会話を開始します。
しかし、それは設計上の決定だ - それは、ソケットのルールではありません。

Now there are two sets of verbs to use for communication. You can use send and recv, or you can transform your client socket into a file-like beast and use read and write. The latter is the way Java presents its sockets. I’m not going to talk about it here, except to warn you that you need to use flush on sockets. These are buffered “files”, and a common mistake is to write something, and then read for a reply. Without a flush in there, you may wait forever for the reply, because the request may still be in your output buffer.

現在通信に使用する動詞の2つのセットがあります。
あなたは、sendとrecv使用するか、読み取りと書き込みファイルのような獣にあなたのクライアントソケットを変換して使用することができます。
後者は、Javaがそのソケットを提示の方法です。
私はあなたがソケット上でフラッシュを使用する必要があることを警告する場合を除き、ここでそれについて話すつもりはありません。
これらは、 "ファイル"を緩衝し、よくある間違いは、応答を読んで、何かを書き、であるされています。
要求がまだ出力バッファにあるかもしれないので、そこにフラッシュすることなく、あなたは、応答を永久に待つかもしれません。

Now we come the major stumbling block of sockets - send and recv operate on the network buffers. They do not necessarily handle all the bytes you hand them (or expect from them), because their major focus is handling the network buffers. In general, they return when the associated network buffers have been filled (send) or emptied (recv). They then tell you how many bytes they handled. It is your responsibility to call them again until your message has been completely dealt with.

今、私たちは、ソケットの主要なつまずきに来る - sendとrecvはネットワークバッファ上で動作します。
彼らは必ずしも彼らの主要な焦点は、ネットワーク·バッファを処理しているので、あなたは、それらを(またはそれらから期待して)手のすべてのバイトを処理しません。
関連付けられたネットワークバッファが(RECV)を充填send()または空にされている場合に一般的に、彼らは戻ります。
そして、彼らは彼らがどのように処理したか多くのバイト数を教えてください。
それはあなたのメッセージが完全に対処されるまで、再度呼び出すことはあなたの責任です。

When a recv returns 0 bytes, it means the other side has closed (or is in the process of closing) the connection. You will not receive any more data on this connection. Ever. You may be able to send data successfully; I’ll talk about that some on the next page.

RECVが0バイトを返す場合、それは反対側(または閉鎖のプロセスにあります)接続を閉じたことを意味します。
この接続上の任意のより多くのデータを受け取ることができません。これまで。
あなたは、正常にデータを送ることができるかもしれません、私は次のページにいくつかのことについて話します。

A protocol like HTTP uses a socket for only one transfer. The client sends a request, then reads a reply. That’s it. The socket is discarded. This means that a client can detect the end of the reply by receiving 0 bytes.

HTTPなどのプロトコルは1つだけ転送するためのソケットを使用しています。
クライアントは、応答を読み取り、次に、要求を送信します。それはそれです。ソケットは破棄されます。
これは、クライアントが0バイトを受信することによって、応答の終わりを検出できることを意味します。

But if you plan to reuse your socket for further transfers, you need to realize that there is no EOT on a socket. I repeat: if a socket send or recv returns after handling 0 bytes, the connection has been broken. If the connection has not been broken, you may wait on a recv forever, because the socket will not tell you that there’s nothing more to read (for now). Now if you think about that a bit, you’ll come to realize a fundamental truth of sockets: messages must either be fixed length (yuck), or be delimited (shrug), or indicate how long they are (much better), or end by shutting down the connection. The choice is entirely yours, (but some ways are righter than others).

あなたがさらに転送用のソケットを再利用する予定がある場合しかし、あなたはソケットにはEOTが存在しないことを認識する必要があります。
私は繰り返し:ソケットの送信または0バイトを処理した後のrecvを返す場合、接続が切断されています。
接続が切断されていない場合、ソケットが(今のところ)を読み取るためのより多くの何もないことを教えてくれませんので、あなたは永遠のrecvを待つことができます。
メッセージがいずれか(不潔な)固定長であるか、または区切り(肩をすくめる)であるか、またはそれらがどのくらいの時間を示している(ずっと)、または必要があります:
あなたは、そのビットを考えれば今、あなたは、ソケットの基本的な真理を実現するために来る接続をシャットダウンして終了します。
選択は完全にあなたの(ただし、いくつかの方法が他よりも正す人です)です。

Assuming you don’t want to end the connection, the simplest solution is a fixed length message:

あなたが接続を終了したくないと仮定すると、最も簡単な解決策は、固定長のメッセージです。

class mysocket:
    '''demonstration class only
      - coded for clarity, not efficiency
    '''

    def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(
                socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

    def connect(self, host, port):
        self.sock.connect((host, port))

    def mysend(self, msg):
        totalsent = 0
        while totalsent < MSGLEN:
            sent = self.sock.send(msg[totalsent:])
            if sent == 0:
                raise RuntimeError("socket connection broken")
            totalsent = totalsent + sent

    def myreceive(self):
        msg = ''
        while len(msg) < MSGLEN:
            chunk = self.sock.recv(MSGLEN-len(msg))
            if chunk == '':
                raise RuntimeError("socket connection broken")
            msg = msg + chunk
        return msg

The sending code here is usable for almost any messaging scheme - in Python you send strings, and you can use len() to determine its length (even if it has embedded \0 characters). It’s mostly the receiving code that gets more complex. (And in C, it’s not much worse, except you can’t use strlen if the message has embedded \0s.)

ここで送信するコードは、ほぼすべてのメッセージング方式のために使用可能です - Pythonで、文字列を送信し、
(これは\ 0文字が埋め込まれている場合でも)、その長さを決定するためにLEN()を使用することができます。
これは主に複雑になっ受信コードです。 
(メッセージは\0が埋め込まれている場合はstrlenを使用することはできませんを除いて、Cで、それははるかに悪化しません。)

The easiest enhancement is to make the first character of the message an indicator of message type, and have the type determine the length. Now you have two recvs - the first to get (at least) that first character so you can look up the length, and the second in a loop to get the rest. If you decide to go the delimited route, you’ll be receiving in some arbitrary chunk size, (4096 or 8192 is frequently a good match for network buffer sizes), and scanning what you’ve received for a delimiter.

最も簡単な拡張は、メッセージの最初の文字メッセージの種類の指標を作成し、タイプは長さを決定することです。
今、あなたは2つのrecvsを持っている - (少なくとも)を取得するために最初にその最初の文字は残りの部分を取得するためのループの長さ、
および秒をルックアップできるように。
区切られたルートを行くことに決める場合は、いくつかの任意のチャンクサイズは、
(4096または8192が頻繁にネットワークバッファサイズの良い試合である)で受信し、
区切り文字のために受け取ったものをスキャンするでしょう。

One complication to be aware of: if your conversational protocol allows multiple messages to be sent back to back (without some kind of reply), and you pass recv an arbitrary chunk size, you may end up reading the start of a following message. You’ll need to put that aside and hold onto it, until it’s needed.

注意すべき一つの合併症:あなたの会話のプロトコルは複数のメッセージが戻って(応答のいくつかの種類を除く)に返送することができ、
あなたは、recv任意のチャンクサイズを渡す場合、次のメッセージの開始を読んで終わる可能性があります。
それが必要になるまではさておき、それを入れて、それを保持する必要があります。

Prefixing the message with it’s length (say, as 5 numeric characters) gets more complex, because (believe it or not), you may not get all 5 characters in one recv. In playing around, you’ll get away with it; but in high network loads, your code will very quickly break unless you use two recv loops - the first to determine the length, the second to get the data part of the message. Nasty. This is also when you’ll discover that send does not always manage to get rid of everything in one pass. And despite having read this, you will eventually get bit by it!

(それを信じるかどうか)を使用すると、1つのrecvの5文字を取得することはできませんので、
それの長さ(5桁の数字のように、と言う)を使用してメッセージを付けることは、もっと複雑になります。
遊んで、あなたはそれで済むでしょう、しかし、2つのrecvのループを使用しない限り、ネットワークの高負荷で、
あなたのコードは非常に迅速に解除されます - メッセージのデータ部分を取得するために長さ、第二を決定する最初の。
厄介な。あなたが送信が常につのパスですべてのものを取り除くために管理していないことを発見するでしょう時でもあります。
そしてこれを読んでいるにもかかわらず、あなたは最終的にそれによって少し得るでしょう!

In the interests of space, building your character, (and preserving my competitive position), these enhancements are left as an exercise for the reader. Lets move on to cleaning up.

あなたのキャラクターは、(私の競争力を維持する)を構築する空間の利益では、これらの拡張機能は、読者の宿題として残されています。
クリーンアップに移ることを許可します。

Binary Data

It is perfectly possible to send binary data over a socket. The major problem is that not all machines use the same formats for binary data. For example, a Motorola chip will represent a 16 bit integer with the value 1 as the two hex bytes 00 01. Intel and DEC, however, are byte-reversed - that same 1 is 01 00. Socket libraries have calls for converting 16 and 32 bit integers - ntohl, htonl, ntohs, htons where “n” means network and “h” means host, “s” means short and “l” means long. Where network order is host order, these do nothing, but where the machine is byte-reversed, these swap the bytes around appropriately.

それは、ソケット経由でバイナリデータを送信するためには完全に可能です。
大きな問題ではないすべてのマシンがバイナリデータに同じフォーマットを使用することです。
たとえば、Motorolaのチップは、2進数のバイト00 01として値1で16ビットの整数を表します。 
IntelおよびDECは、しかし、バイト反転します - 同じ1が01 00であること。
 ntohl、でhtonl、ntohsを、"n"はネットワークとの "h"を意味はhtonsは、ホストを意味し、
 "s"が短いと"L"の長い手段 - ソケットライブラリは16ビットと32ビットの整数に変換するためのコールを持っています。
ネットワークの順序は、ホストの順序である場合、これらは何もしませんが、適切に周りのマシンがバイト反転され、これらのスワップのバイトを。

In these days of 32 bit machines, the ascii representation of binary data is frequently smaller than the binary representation. That’s because a surprising amount of the time, all those longs have the value 0, or maybe 1. The string “0” would be two bytes, while binary is four. Of course, this doesn’t fit well with fixed-length messages. Decisions, decisions.

32ビットマシンの時代では、バイナリデータのASCII表現をバイナリ表現よりも頻繁に小さくなっています。
時間の驚くべき量は、これらすべてのlong型は多分1を値0を持っているか、からだ。
バイナリが4である一方で、文字列"0"は、2バイトになります。
もちろん、これは固定長のメッセージとよく適合しません。決定、決定。

Disconnecting

Strictly speaking, you’re supposed to use shutdown on a socket before you close it. The shutdown is an advisory to the socket at the other end. Depending on the argument you pass it, it can mean “I’m not going to send anymore, but I’ll still listen”, or “I’m not listening, good riddance!”. Most socket libraries, however, are so used to programmers neglecting to use this piece of etiquette that normally a close is the same as shutdown(); close(). So in most situations, an explicit shutdown is not needed.

厳密に、あなたはそれを閉じる前に、ソケットにshutdownを使用することになって、いる話す。
シャットダウンは、もう一方の端にあるソケットの諮問である。
あなたがそれを渡す引数に応じて、それは "私はもう送信するつもりはありませんが、私はまだ聞いてよ"を意味します
"私は、いい厄介払いを聞いていないよ!"、または。
ほとんどのソケットライブラリは、しかし、これを正常に閉じるshutdown()が同じであることを
エチケットのこの部分を使用するように無視してプログラマに使用されます。
close()を。ほとんどの状況でできるように、明示的なシャットダウンは必要ありません。

One way to use shutdown effectively is in an HTTP-like exchange. The client sends a request and then does a shutdown(1). This tells the server “This client is done sending, but can still receive.” The server can detect “EOF” by a receive of 0 bytes. It can assume it has the complete request. The server sends a reply. If the send completes successfully then, indeed, the client was still receiving.

シャットダウンを使用する方法の1つは、効果的にHTTPのような交換である。
クライアントが要求を送信し、シャットダウン(1)を行います。
これは、サーバーが、 "このクライアントは、送信が行われていますが、まだ受け取ることができます。
"サーバーが0バイト受信で"EOF"を検出することができます指示します。
それは完全な要求を持っていると仮定することができます。
サーバは応答を送信します。送信が正常に次に完了した場合、確かに、クライアントはまだ受け取っていた。

Python takes the automatic shutdown a step further, and says that when a socket is garbage collected, it will automatically do a close if it’s needed. But relying on this is a very bad habit. If your socket just disappears without doing a close, the socket at the other end may hang indefinitely, thinking you’re just being slow. Please close your sockets when you’re done.

Pythonは、さらに一歩自動シャットダウンを受け取り、それが必要なの場合は、ソケットはガベージコレクトされるとき、
それは自動的にクローズを行うとしている。しかし、これに頼るのは非常に悪い習慣です。
ソケットがちょうど近くにせず消えた場合、もう一方の端にあるソケットはあなただけで遅いだと考え、無期限にハングする可能性があります。
設定が完了したら、あなたのソケットを閉じてください。

When Sockets Die

Probably the worst thing about using blocking sockets is what happens when the other side comes down hard (without doing a close). Your socket is likely to hang. SOCKSTREAM is a reliable protocol, and it will wait a long, long time before giving up on a connection. If you’re using threads, the entire thread is essentially dead. There’s not much you can do about it. As long as you aren’t doing something dumb, like holding a lock while doing a blocking read, the thread isn’t really consuming much in the way of resources. Do not try to kill the thread - part of the reason that threads are more efficient than processes is that they avoid the overhead associated with the automatic recycling of resources. In other words, if you do manage to kill the thread, your whole process is likely to be screwed up.

おそらくブロッキングソケットを使用する方法について最悪の事はもう一方の側は、ハードダウンしてときに何が(クローズを行わずに)起こります。
あなたのソケットがハングする可能性があります。 
SOCKSTREAMは信頼性の高いプロトコルであり、それが接続をあきらめる前に長い、長い時間を待っています。
あなたはスレッドを使用している場合は、スレッド全体は本質的に死んでいる。
ずっとあなたがそれについて行うことができますがありません。
あなたがブロック読み取りをしながらロックを保持しているようなダム何かを行っていない限り、スレッドがリソースの方法で多くを実際にかかるではありません。
スレッドを殺すためにしようとしない - のスレッドはプロセスよりも効率的であることを理由の一部は、
リソースの自動リサイクルに関連するオーバーヘッドを避けることです。
あなたはスレッドを殺すために管理を行う言い換えれば、あなたの全体のプロセスが台無しにされる可能性がある。

Non-blocking Sockets

If you’ve understood the preceding, you already know most of what you need to know about the mechanics of using sockets. You’ll still use the same calls, in much the same ways. It’s just that, if you do it right, your app will be almost inside-out.

前のを理解している場合は、すでにほとんどは、ソケットを使用しての仕組みについて知っておく必要があるのを知っています。
あなたはまだほとんど同じ方法で、同じコールを使用します。
それはあなたが右のそれをすれば、あなたのアプリケーションはほとんどインサイドアウトになり、というだけです。

In Python, you use socket.setblocking(0) to make it non-blocking. In C, it’s more complex, (for one thing, you’ll need to choose between the BSD flavor O_NONBLOCK and the almost indistinguishable Posix flavor O_NDELAY, which is completely different from TCP_NODELAY), but it’s the exact same idea. You do this after creating the socket, but before using it. (Actually, if you’re nuts, you can switch back and forth.)

Pythonでは、あなたはそれが非ブロッキングにする(0)socket.setblocking使用しています。 
Cでは、それは(一つには、BSDフレーバーO_NONBLOCKとTCP_NODELAYとは全く異なる、
ほとんど見分けがつかないのPosix風味O_NDELAY、どちらかを選択する必要があります)、
もっと複雑だが、それはまったく同じ考えです。
あなたは、ソケットを作成した後、それを使用する前にこれを行います。 
(あなたがナッツなら実際には、あなたが行ったり来たり切り替えることができます。)

The major mechanical difference is that send, recv, connect and accept can return without having done anything. You have (of course) a number of choices. You can check return code and error codes and generally drive yourself crazy. If you don’t believe me, try it sometime. Your app will grow large, buggy and suck CPU. So let’s skip the brain-dead solutions and do it right.

主要な機械的な違いがあることが、recvを送信接続すると、何も行わずに返すことができますを受け入れることです。
あなたは(もちろん)選択肢の数を持っています。
あなたは、リターンコードとエラーコードを確認し、一般的に狂った自分自身を駆動することができます。
あなたは私を信じていない場合は、いつかそれを試してみてください。
あなたのアプリケーションは、大規模な、バギーを成長させ、CPUを吸うされます。
それでは、脳死ソリューションをスキップして、右のそれをやらせる。

Use select.

選択してください。

In C, coding select is fairly complex. In Python, it’s a piece of cake, but it’s close enough to the C version that if you understand select in Python, you’ll have little trouble with it in C:

Cでは、コーディングを選択してはかなり複雑です。 
Pythonでは、それはケーキの一部ですが、それはあなたがPythonで選択して理解していれば、
あなたがC言語でそれに少し問題が発生しなければならないということを十分に近いCバージョンに次のとおりです。

ready_to_read, ready_to_write, in_error = \
               select.select(
                  potential_readers,
                  potential_writers,
                  potential_errs,
                  timeout)

You pass select three lists: the first contains all sockets that you might want to try reading; the second all the sockets you might want to try writing to, and the last (normally left empty) those that you want to check for errors. You should note that a socket can go into more than one list. The select call is blocking, but you can give it a timeout. This is generally a sensible thing to do - give it a nice long timeout (say a minute) unless you have good reason to do otherwise.

あなたは、選択の3つのリストを渡します。
最初にあなたが読書をしようとする場合がありますしているすべてのソケットが含まれています。
あなたへの書き込みをしようとする場合があります第二すべてのソケットと、最後の(通常は空のまま)では、
エラーをチェックしたいものを。
あなたは、ソケットが複数のリストに行くことができることに注意してください。 
selectシステムコールはブロックされていますが、あなたはそれをタイムアウトを与えることができます。
これは一般的に行うための賢明なことです - あなたは、そうでなければ行うには良い理由がない限り、
それは素敵な長いタイムアウト(分と言う)を与えます。

In return, you will get three lists. They contain the sockets that are actually readable, writable and in error. Each of these lists is a subset (possibly empty) of the corresponding list you passed in.

リターンでは、3つのリストを取得します。
彼らは実際に読み取り可能、書き込み可能とエラーが発生しているソケットが含まれています。
これらの各リストは、あなたが渡された対応するリストのサブセット(空の可能性もある)です。

If a socket is in the output readable list, you can be as-close-to-certain-as-we-ever-get-in-this-business that a recv on that socket will return something. Same idea for the writable list. You’ll be able to send something. Maybe not all you want to, but something is better than nothing. (Actually, any reasonably healthy socket will return as writable - it just means outbound network buffer space is available.)

ソケットは出力読み取り可能なリストである場合、
あなたはできるようにクローズ·ツー·特定·アズ·我々は史上-getで-このビジネスで、そのソケット上でrecvを何かを返すこと。
書き込み可能なリストについては、同じアイデア。何かを送ることができるようになります。
そうでないかもしれないあなたがしたいのですが、何かが何よりも優れているすべての。 
(実際には、任意の合理的に健康なソケットが書き込み可能として返します
 - それはちょうど、発信ネットワークバッファ領域が使用可能であることを意味します。)

If you have a “server” socket, put it in the potential_readers list. If it comes out in the readable list, your accept will (almost certainly) work. If you have created a new socket to connect to someone else, put it in the potential_writers list. If it shows up in the writable list, you have a decent chance that it has connected.

あなたは"サーバ"ソケットを使用している場合は、potential_readersリストに入れてください。
それが読み取り可能なリストに出てくる場合には、あなたのウィル(ほぼ確実に)仕事を受け入れます。
あなたが他の誰かに接続するための新しいソケットを作成している場合は、potential_writersリストに入れてください。
それが書き込み可能なリストに表示されている場合、あなたはそれが接続されていることをまともなチャンスがあります。

One very nasty problem with select: if somewhere in those input lists of sockets is one which has died a nasty death, the select will fail. You then need to loop through every single damn socket in all those lists and do a select([sock],[],[],0) until you find the bad one. That timeout of 0 means it won’t take long, but it’s ugly.

ひとつの非常に厄介な問題は、選択します。
どこかのソケットのこれらの入力リスト内の不快な死を遂げたものである場合、selectは失敗します。
次に、すべてのこれらのリスト内のすべての単一いまいましいソケットを介してループする必要があり、
選択を行う([sock]、[]、[]、0)あなたは悪いものを見つけるまで。 
0にすると、そのタイムアウトが、それは長くはかからないでしょうが、それは醜いです。

Actually, select can be handy even with blocking sockets. It’s one way of determining whether you will block - the socket returns as readable when there’s something in the buffers. However, this still doesn’t help with the problem of determining whether the other end is done, or just busy with something else.

実際に、選択してもブロッキングソケットと便利です。
それはあなたがブロックするかどうかを判断する一つの方法です - バッファ内の何かがあるときソケットは、読みやすくを返します。
しかし、これはまだ何か他のもののちょうど忙しいもう一方の端が行われるかどうかを決定する問題に役立つか、ではありません。

Portability alert: On Unix, select works both with the sockets and files. Don’t try this on Windows. On Windows, select works with sockets only. Also note that in C, many of the more advanced socket options are done differently on Windows. In fact, on Windows I usually use threads (which work very, very well) with my sockets. Face it, if you want any kind of performance, your code will look very different on Windows than on Unix.

移植性の警告:
Unixでは、selectはソケットとファイルの両方で動作します。 
Windows上でこれを試していません。 
Windows上で、ソケットだけで動作を選択します。
また、C言語で、より高度なソケットオプションの多くはWindowsで異なった方法で行われることに注意してください。
実際には、Windows上で私は通常のソケットでスレッドを(非常に、非常にうまく機能している)を使用します。
あなたは、パフォーマンスのあらゆる種類の場合は、それに直面して、あなたのコードはUnix上ではなく、
Windows上で非常に異なって見えます。

Performance

There’s no question that the fastest sockets code uses non-blocking sockets and select to multiplex them. You can put together something that will saturate a LAN connection without putting any strain on the CPU. The trouble is that an app written this way can’t do much of anything else - it needs to be ready to shuffle bytes around at all times.

最速のソケットコードはノンブロッキングソケットを使用し、多重化、それらをに選択することに疑いはありません。
あなたは、CPU上の任意の負担をかけることなく、LAN接続を飽和させる何かを一緒に置くことができます。
トラブルは、このように書かれたアプリは何かの多くを行うことができないということです 
- 常に周りにシャッフルバイトに準備ができて、それは必要があります。

Assuming that your app is actually supposed to do something more than that, threading is the optimal solution, (and using non-blocking sockets will be faster than using blocking sockets). Unfortunately, threading support in Unixes varies both in API and quality. So the normal Unix solution is to fork a subprocess to deal with each connection. The overhead for this is significant (and don’t do this on Windows - the overhead of process creation is enormous there). It also means that unless each subprocess is completely independent, you’ll need to use another form of IPC, say a pipe, or shared memory and semaphores, to communicate between the parent and child processes.

あなたのアプリケーションが実際にそれ以上の何かをすることになっていると仮定すると、
スレッドが(高速ブロッキングソケットを使用するよりもなりますし、非ブロッキングソケットを使用して)、
最適なソリューションです。
残念ながら、のUnixのサポートをスレッドとAPIと品質の両方によって異なります。
ので、通常のUnixのソリューションは、各接続に対処するためにサブプロセスをforkすることです。
このためのオーバーヘッドは( - プロセス生成のオーバーヘッドが膨大であり、Windowsでこれを行うにはありません)
重要である。
また、各サブプロセスが完全に独立していない限り、あなたは、IPCの別のフォームを使用する必要があります
パイプを言うか、メモリとセマフォを共有し、親プロセスと子プロセス間の通信にあることを意味します。

Finally, remember that even though blocking sockets are somewhat slower than non-blocking, in many cases they are the “right” solution. After all, if your app is driven by the data it receives over a socket, there’s not much sense in complicating the logic just so your app can wait on select instead of recv.

最後に、ブロッキングソケットは非ブロッキングよりも多少遅くなりますにもかかわらず、多くの場合、
彼らは"正しい"解決策であることを覚えています。
あなたのアプリケーションは、ソケット経由で受信したデータで駆動されている場合、すべての後、
あまり意味はあなたのアプリケーションは、代わりにrecvを選択するのに待つことができるだけのように
ロジックを複雑に存在しません。

タグ:

+ タグ編集
  • タグ:
最終更新:2012年02月03日 17:04
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。

*1 '', 80

*2 'localhost', 80

*3 '127.0.0.1', 80