2016-12-10 13 views
0

スーパーシンプルなJSON-RPCサーバーを構築しようとしていますが、POSTメッセージの本文を受信できません。引数がホストヘッダーに含まれているので、GETメッセージを正常に受信できます。しかし、私はPOSTまたはPUTのいずれかの本体を受け取ることはできません。私は実際に適切なPOSTメッセージを送信していることを確認するために、PostmanとcUrlという2つの異なるバージョンを使用しました。ソケットでHTTP本体を受信して​​いません

私のコードはかなりシンプルです。私はソケットを作成し、それにバインドして、受け取ったものを聞いて保存します。 (PはProgramクラスへの参照です)

p.sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); 
p.sock.Bind(new IPEndPoint(IPAddress.Any, p.config.server_port)); 
p.sock.Listen(5); 
p.serverThread = new Thread(new ThreadStart(() => serverListen(p))); 
p.serverThread.Start(); 

、その後、私は実際にメッセージを受信するために、次のブロックを使用します。

Socket recieved = p.sock.Accept(); 
//handle recieved info 
string message = ""; 
byte[] buffer = new byte[10000]; 
int readResult = recieved.Receive(buffer); 
if (readResult > 0) { 
    message = Encoding.UTF8.GetString(buffer,0, readResult); 
    message = message;//for debugging purposes 
    message = ReceivedMessage.decodeURL(message);//Get rid of URL encoding 
} 

これはGETメッセージの素晴らしい作品が、体を返すことに失敗しましたPOSTメッセージ用。上記のコードは、次のHTTPメッセージを取得します。

POST/HTTP/1.1 
cache-control: no-cache 
Postman-Token: 5dab0e8e-910f-4c5d-a7dd-49bf5348a8d0 
Content-Type: text/plain 
User-Agent: PostmanRuntime/3.0.5 
Accept: */* 
Host: localhost:1215 
accept-encoding: gzip, deflate 
content-length: 18 
Connection: keep-alive 

ボディー要素はまったく含まれていません。私は何が欠けていますか?どんな助けでも大歓迎です。

答えて

0

HTTPヘッダーが最初に送信されるというエラーがあったため、その後本文が送信されます。それとも少なくとも私はそれが起こっていると思います。したがって、本文を読むためには、本文テキストを取得するために、Socket.Recieve()(またはAsyncバージョン)をもう一度呼び出す必要があります。これは次のようになります:

//get the rest of the body 
string httpBody = string.Empty; 
byte[] bodyBuffer = new byte[10000]; //arbitrary buffer length 
string[] lines = message.Split('\n'); //split the header Message by newlines 
string StrLength = string.Empty; 
int contentLength = 0; 
foreach (string line in lines) { 
    if (line.Contains("content-length")) { 
     string[] splitLine = line.Split(':'); 
     StrLength = splitLine[1]; 
     break; 
    } 
} 
if (StrLength != null) { 
    try { 
     contentLength = int.Parse(StrLength); 
    } 
    catch { 
     Console.WriteLine("Failed to parse content-length"); 
    } 
} 
else { 
    Console.WriteLine("content-length header not found"); 
} 
int bodyReadResult = sock.Receive(bodyBuffer); 
if (bodyReadResult != contentLength) { 
    Console.WriteLine("Failed to read all of HTTP body, probably sent as a multipart"); 
} 
httpBody = Encoding.ASCII.GetString(bodyBuffer, 0, bodyReadResult); 
関連する問題