由 Programming C# 3.0 示例改编
AsyncNetClient.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace AsyncNetClient
{
public class AsynchNetworkClient
{
private NetworkStream streamToServer;
static public int Main()
{
string str;
Console.Write("input:");
str = Console.ReadLine();
if (str.Length > 20)
{
Console.WriteLine("提示: 输入字符串长度 <= 20");
return 4;
}
AsynchNetworkClient client = new AsynchNetworkClient("localhost",65000);
if( client != null && str!=null) return client.Run(str);
else return 4;
}
public AsynchNetworkClient(string ip, int port)
{
string serverName = ip;
try
{
Console.WriteLine("Connecting to {0}", serverName);
TcpClient tcpSocket = new TcpClient(serverName, port);
streamToServer = tcpSocket.GetStream();
}
catch (Exception e){
Console.WriteLine(e.ToString());
}
}
public int Run(string str)
{
if (streamToServer == null)
{
Console.WriteLine("connect to Server failed !");
return -1;
}
string message;
if( str != "") message= str;
else return -1;
Console.WriteLine("Send to server: {0}", message);
// create a streamWriter and use it to
// write a string to the server
StreamWriter writer = new StreamWriter(streamToServer);
writer.WriteLine(message);
writer.Flush();
// 使用System.Text.Encoding.Default 告诉 StreamReader采用目前操作系统的编码即可
StreamReader reader = new StreamReader(streamToServer,Encoding.Default);
string strResponse = reader.ReadLine();
streamToServer.Close();
Console.WriteLine("Received: {0}", strResponse);
return 0;
}
}
}
编译 csc.exe AsyncNetClient.cs
运行 AsyncNetClient.exe