TCP通讯协议(上)同步传输
直接上例子,学习资料来自NET之美。服务端创建Listener对象,客户端创建Client对象,服务端首先开始对本地端口监听,客户端发送连接请求。当需要传输字符串时,两者均需要创建Stream对象,将想说的话,写在这片小红叶上,小红叶就飞到对方哪里了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ConsoleTest
{
class Server
{
static void Main(string [] args)
{
Console.WriteLine("Server is running");
const int buffersize =6;
IPAddress ip = IPAddress.Parse("127.0.0.1");
//IPAddress ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
TcpListener listener = new TcpListener(ip,8500);
listener.Start();
TcpClient remoteclient = listener.AcceptTcpClient();//同步方法,读取同意客户端多个信息
Console.WriteLine("Client{0} connects to--->Server{1}", remoteclient.Client.RemoteEndPoint, remoteclient.Client.LocalEndPoint);
NetworkStream streamToClient = remoteclient.GetStream();
do
{ //read data
try {//防止客户端阻塞在read()方法处,要把命令写在try catch中
byte[] buffer = new byte[buffersize];
MemoryStream ms = new MemoryStream();
int byteread;
byteread = streamToClient.Read(buffer, 0, buffersize);
if (byteread == 0)//客户端调用Close()和Dispose()方法时,服务端的Read()方法会持续返回0
{ Console.WriteLine("Client Offline"); break; }
string msg = Encoding.Unicode.GetString(buffer, 0, buffersize);
Console.WriteLine("Recieve:{0}[{1}Bytes]", msg, byteread);
//send data
msg = msg.ToUpper();
Console.WriteLine("send:{0}", msg);
buffer = Encoding.Unicode.GetBytes(msg);
streamToClient.Write(buffer, 0, buffer.Length);}
catch (Exception ex)
{
Console.WriteLine(ex.Message);break;
}
} while (true);
streamToClient.Dispose();
remoteclient.Close();
//按Q退出
ConsoleKey key;
do
{
key = Console.ReadKey(true).Key;
} while (key != ConsoleKey.Q);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Client
{
class Client
{
static void Main(string[] args)
{
Console.WriteLine("Client is running");
const int buffersize = 6;
TcpClient client;
try {
client = new TcpClient();
IPAddress ip = IPAddress.Parse("127.0.0.1");
//IPAddress ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
client.Connect(ip,8500);
}
catch(Exception ex) { Console.WriteLine(ex.Message);
return;
}
Console.WriteLine("Client{0} connects to--->Server{1}", client.Client.RemoteEndPoint, client.Client.LocalEndPoint);
NetworkStream streamToServer = client.GetStream();
string msg;
do
{ //read data from screen
Console.WriteLine("Sent:");
msg= Console.ReadLine();
if(!string.IsNullOrEmpty(msg)&& msg != "Q")
{
byte[] buffer = Encoding.Unicode.GetBytes(msg);
try
{
streamToServer.Write(buffer, 0,buffer.Length);//send
int bytesread;
buffer = new byte[buffersize];
//recieve
bytesread=streamToServer.Read(buffer, 0, buffersize);
if (bytesread == 0) { Console.WriteLine("Server is offline");break; }
msg = Encoding.Unicode.GetString(buffer,0, bytesread);
Console.WriteLine("Recieved:{0} [{1}]",msg,bytesread);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); break;
}
}
} while (msg != "Q");
streamToServer.Dispose();
client.Close();
}
}
}