扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:谢启东编译 来源:天极开发 2007年11月16日
关键字:
using namespace System; using namespace System::IO; using namespace System::Net; using namespace System::Net::Sockets; using namespace System::Threading; int main(array<String^>^ argv) { if (argv->Length != 2) { Console::WriteLine("Usage: Client port message-count"); Environment::Exit(1); } int port = 0; try { port = Int32::Parse(argv[0]); } catch (FormatException^ e) { Console::WriteLine("Port number {0} is ill-formed", argv[0]); Environment::Exit(2); } if (port < IPEndPoint::MinPort || port > IPEndPoint::MaxPort) { Console::WriteLine("Port number must be in the range {0}-{1}",IPEndPoint::MinPort, IPEndPoint::MaxPort); Environment::Exit(3); } int messageCount = 0; try { messageCount = Int32::Parse(argv[1]); } catch (FormatException^ e) { Console::WriteLine("Message count {0} is ill-formed", argv[1]); Environment::Exit(4); } IPAddress^ ipAddress = nullptr; try { /*1*/ ipAddress = Dns::GetHostEntry(Dns::GetHostName())->AddressList[0]; /*2*/ IPEndPoint^ ipEndpoint = gcnew IPEndPoint(ipAddress, port); /*3*/ Socket^ clientSocket = gcnew Socket(AddressFamily::InterNetwork, SocketType::Stream, ProtocolType::Tcp); /*4*/ clientSocket->Connect(ipEndpoint); NetworkStream^ netStream = gcnew NetworkStream(clientSocket); BinaryReader^ br = gcnew BinaryReader(netStream); BinaryWriter^ bw = gcnew BinaryWriter(netStream); int value1, value2; int result; Random^ random = gcnew Random; (int i = 1; i <= messageCount; ++i) { /*5*/ value1 = static_cast<int>(random->NextDouble() * 100); /*6*/ value2 = static_cast<int>(random->NextDouble() * 100); /*7*/ bw->Write(value1); /*8*/ bw->Write(value2); Console::Write("Sent values {0,3} and {1,3}",value1, value2); /*9*/ result = br->ReadInt32(); Console::WriteLine(", received result {0,3}", result); /*10*/ Thread::Sleep(3000); } /*11*/ clientSocket->Shutdown(SocketShutdown::Both); Console::WriteLine("Notified server we're shutting down"); /*12*/ clientSocket->Close(); /*13*/ netStream->Close(); Console::WriteLine("Shutting down client"); } /*14*/ catch (SocketException^ e) { Console::WriteLine("Request to connect to {0} on port {1} failed"+ "\nbecause of {2}", ipAddress, port, e); Environment::Exit(5); } } |
Server listener blocking status is True New connection accepted Received values 42 and 69, sent result 111 Received values 66 and 71, sent result 137 Received values 7 and 93, sent result 100 Received values 43 and 65, sent result 108 Received values 45 and 3, sent result 48 Shutting down server |
Sent values 42 and 69, received result 111 Sent values 66 and 71, received result 137 Sent values 7 and 93, received result 100 Sent values 43 and 65, received result 108 Sent values 45 and 3, received result 48 Notified server we're shutting down Shutting down client |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者