前提・実現したいこと
CentOSを利用しています。
ソケット通信プログラムで
クライアントとサーバ間でメッセージを送受信すること実現したいです。
その際に、メッセージをクラスのオブジェクトで送信を考えています。
メッセージクラスは、識別子(uint32_t)とメッセージ(char)をメンバ変数としています。
今回のエラーは、オブジェクトを送信した時に、
識別子はサーバ側で受け取り出力できますが、
メッセージは、ポインタのアドレスが送信されており、
標準入力で読み取った内容が送信できません。
そこで、サーバ側でメッセージの内容(標準入力)を表示させるには
どのように修正すればよいでしょうか?
発生している問題・エラーメッセージ
エラーメッセージ
該当のソースコード
C++
ソースコード(client.cpp)
#include <stdio.h> #include <string.h> #include <netdb.h> #include <iostream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> using namespace std; class Message{ public: uint32_t a; char *b; Message(char *message,uint32_t i){ a = i; b = message; } ~Message(){} void print(){ cout << "header : " << hex << a << endl; cout << "char : " << b << endl; } }; int main() { int c_fd,s_fd=0; char message[1024]; struct sockaddr_in server; memset(message, '0',sizeof(message)); if((c_fd = socket(AF_INET,SOCK_STREAM, 0)) < 0){ cout << "socket()" << endl; return 1; } server.sin_family = AF_INET; server.sin_port = htons(32960); server.sin_addr.s_addr = inet_addr("127.0.0.1"); if(connect(c_fd, (struct sockaddr *)&server,sizeof(server)) < 0){ cout << "coonect()" << endl; return 1; } cout << ">client : "; cin >> message; Message msg(message,0x11111111); char* tmp = reinterpret_cast<char*>(&msg); msg.print(); ssize_t sn; if((sn=send(c_fd,tmp,sizeof(Message),0))< 0){ cout << "send()" << endl; } cout << sn << " byte send to sever." << endl; close(c_fd); return 0; }
ソースコード(server.cpp)
#include <stdio.h> #include <string.h> #include <netdb.h> #include <iostream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> using namespace std; class Message{ public: uint32_t a; char *b; Message(){} ~Message(){} void print(){ cout << "header : " << hex << a << endl; cout << "char : " << b << endl; } }; int main(){ struct sockaddr_in server,client; int s_fd,c_fd; socklen_t len = sizeof(struct sockaddr_in); char message[1024]; if((s_fd = socket(AF_INET,SOCK_STREAM,0)) < 0){ cout << "socket()" << endl; return 1; } server.sin_family = AF_INET; server.sin_port = htons(32960); server.sin_addr.s_addr = INADDR_ANY; if((bind(s_fd,(struct sockaddr *)&server, sizeof(server))) < 0){ cout << "bind()" << endl; return 1; } if(listen(s_fd,5) < 0){ cout << "listen()" << endl; return 1; } if((c_fd = accept(s_fd,(struct sockaddr *)&client,&len)) < 0){ cout << "accept()" << endl; return 1; } char buf[sizeof(Message)]; ssize_t rn; if((rn=recv(c_fd,buf,sizeof(Message),0)) < 0){ cout << "recv()" << endl; return 1; } cout << rn << " byte received from client !!" << endl; //cout << buf << endl; Message *msg = reinterpret_cast<Message*>(buf); msg->print(); close(s_fd); close(c_fd); return 0; }
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。