TCP通信のやり取りをするプログラムを作りたいと思っています。
クライアント側はC#、サーバ側はCを使い、
「クライアントがメッセージを送り、サーバーはクライアントに"hello"と返す。これをクライアントが"exit"と送るまで繰り返す。」
というコンソールアプリを作りましたが、"exit"以外のメッセージを送る場合にクライアントがメッセージを受け取ることができず、そこから動かなくなってしまいます。
上記の問題の原因と、ちゃんとサーバーからのメッセージを受け取ることができるようにするにはどうすればよいのかをご教授願います。
###コンソール表示
クライアント側
enter message: abcde (ここから動かない。ctrl+cで終了し、再実行) enter message: exit response message: hello end.
サーバー側
abcde sent :hello exit sent :hello
###ソースコード
C#
1//クライアント側 2using System; 3using System.IO; 4using System.Net; 5using System.Net.Sockets; 6using System.Text; 7 8public class Client { 9 public static void Main() { 10 string sendMsg = ""; 11 string host = "xxx.xxx.xxx.xxx";//IPアドレスは省略 12 int port = 7777; 13 14 TcpClient tcp = new TcpClient(host, port); 15 NetworkStream stream = tcp.GetStream(); 16 17 MemoryStream ms = new MemoryStream(); 18 byte[] resBytes = new byte[256]; 19 int resSize = 0; 20 21 do { 22 Console.WriteLine("enter message: "); 23 sendMsg = Console.ReadLine()+"\0"; 24 byte[] sendBytes = Encoding.UTF8.GetBytes(sendMsg); 25 Console.WriteLine("send message: " + sendMsg); 26 stream.Write(sendBytes, 0, sendBytes.Length); 27 28 do { 29 resSize = stream.Read(resBytes, 0, resBytes.Length); 30 if (resSize == 0) { 31 break; 32 } 33 ms.Write(resBytes, 0, resSize); 34 } while (stream.DataAvailable || resBytes[resSize - 1] != '\n'); 35 36 string resMsg = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length); 37 Console.WriteLine("response message: " + resMsg); 38 } while (sendMsg != "exit\0"); 39 40 Console.WriteLine("end."); 41 Console.ReadLine(); 42 43 ms.Close(); 44 stream.Close(); 45 tcp.Close(); 46 } 47}
C
1//サーバー側 2#include <stdio.h> 3#include <string.h> 4#include <sys/types.h> 5#include <sys/socket.h> 6#include <netinet/in.h> 7 8int main() 9{ 10 int sock0; 11 struct sockaddr_in addr; 12 struct sockaddr_in client; 13 int len; 14 int sock; 15 char buf[128]; 16 char sendMsg[256] = "hello"; 17 18 sock0 = socket(AF_INET, SOCK_STREAM, 0); 19 20 addr.sin_family = AF_INET; 21 addr.sin_port = htons(7777); 22 addr.sin_addr.s_addr = INADDR_ANY; 23 24 bind(sock0, (struct sockaddr *)&addr, sizeof(addr)); 25 26 do { 27 listen(sock0, 5); 28 29 len = sizeof(client); 30 sock = accept(sock0, (struct sockaddr *)&client, &len); 31 32 int recvMsglen; 33 recvMsglen = recv(sock, buf, sizeof(buf), 0); 34 printf("%s\n", buf); 35 36 write(sock, sendMsg, sizeof(sendMsg)); 37 printf("sent :%s\n", sendMsg); 38 39 }while (strcmp(buf, "exit") != 0); 40 41 close(sock); 42 close(sock0); 43 44 return 0; 45}
回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/23 02:18
2019/08/23 02:46
2019/08/23 03:15
2019/08/23 08:03