Skip to content

Instantly share code, notes, and snippets.

@ochilab
Created June 22, 2013 00:43
Show Gist options
  • Save ochilab/5835339 to your computer and use it in GitHub Desktop.
Save ochilab/5835339 to your computer and use it in GitHub Desktop.
Socketでサーバに文字列とバイナリを送信するクライアントプログラム
private: System::Void SocketClient() {
Socket ^mySocket;
NetworkStream ^myStream;
StreamWriter ^myWriter;
BinaryWriter ^myBWriter;
IPAddress ^myAddress;
IPHostEntry ^myHostEntry;
int myPort;
int size;
int count;
IPEndPoint ^myEndPoint;
//文字コードを指定する
System::Text::Encoding^ enc = System::Text::Encoding::UTF8;
//ソケットの作成と接続
mySocket = gcnew Socket(AddressFamily::InterNetwork, SocketType::Stream, ProtocolType::Tcp);
myHostEntry = Dns::Resolve("localhost");
myAddress = myHostEntry->AddressList[0];
myPort = 55555;
myEndPoint = gcnew IPEndPoint(myAddress, myPort);
mySocket->Connect(myEndPoint);
myStream = gcnew NetworkStream(mySocket);
myWriter = gcnew StreamWriter(myStream, Encoding::UTF8);
myBWriter = gcnew BinaryWriter(myStream);
//サーバーにデータを送信する
//送信するデータを入力
String^ sendMsg = "0\n";
//文字列をByte型配列に変換
array<Byte>^ sendBytes = enc->GetBytes(sendMsg);
size = safe_cast<int>(sendBytes->Length);
myWriter->WriteLine(sendMsg);
for (count = 0; count < size; count++){
myBWriter->Write(sendBytes[count]);
}
mySocket->Close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment