using System;
using System.Text;
using
using
//服务端
class S
{
static void Main()
{
//缓存
const int BSize = 8192;
Console.WriteLine("服务端");
//设ip和端口
IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
TcpListener list = new TcpListener(ip, 8800);
listener.Start();
//开始侦听
Console.WriteLine("开始侦听");
TcpClient TC = list.AcceptTcpClient();
// 获得流
NetworkStream NS = TC.GetStream();
byte[] BString = new byte[BSize];
int bytesRead = NS.Read(BString, 0, BSize);
Console.WriteLine("字节:{0} bytes ...", bytesRead);
// 获得请求的字符串
string msg = Encoding.Unicode.GetString(BString, 0, bytesRead);
Console.WriteLine("收到:{0}", msg);
//退出Q
Console.WriteLine("\n\n输入\"Q\"键退出。");
ConsoleKey key;
do
{
key = Console.ReadKey(true).Key;
} while (key != ConsoleKey.Q);
}
}
;=====================================================================================
using System;
using System.Text;
using
using
//客户端
class C
{
static void Main()
{
Console.WriteLine("客务端");
TcpClient cline;
// 与服务器连接
try
{
cline = new TcpClient();
cline.Connect("localhost", 8800);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
string msg = "\"其实我在潜水,请不要抛弃我\"";
//发往服务器
NetworkStream streamToServer = client.GetStream();
byte[] BString = Encoding.Unicode.GetBytes(msg);
streamToServer.Write(BString, 0, BString.Length);
Console.WriteLine("发送:{0}", msg);
//退出Q
Console.WriteLine("\n\n输入\"Q\"键退出。");
ConsoleKey key;
do
{
key = Console.ReadKey(true).Key;
} while (key != ConsoleKey.Q);
}
}
;================================================================================
以上是很经典的同步方式(只显示一次)
还有一些是异步方式,比较麻烦,自己找资料吧
[
本帖最后由 afdoa83 于 2013-7-6 15:23 编辑 ]