直接上例子,学习资料来自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.Accept