客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace tcpclient
{
class Program
{
static void Main(string[] args)
{
//当我们创建tcpclient对象的时候,就会跟server建立连接
TcpClient client = new TcpClient("192.168.3.41",7788);
NetworkStream stream = client.GetStream();//通过网络流进行数据交换
while (true)
{
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);
}
stream.Close();
client.Close();
Console.ReadKey();
}
}
}
服务器端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace tcplistener
{
class Program
{
static void Main(string[] args)
{
//TcpListener对Socket进行了一层封装,这个类里面自己会去创建socket对象
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.3.41"), 7788);
//开始进行监听
listener.Start();
//等待客户端链接过来
TcpClient client = listener.AcceptTcpClient();
//取得客户端发送过来的数据
NetworkStream stream= client.GetStream(); //得到了网络流,从这个网络流可以取得客户端发送过来的数据
byte[] data = new byte[1024];
while (true)
{
int length = stream.Read(data, 0, 1024);//读取数据 1024表示最大读取字节数
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("收到了消息:" + message);
}
stream.Close();
client.Close();
listener.Stop();
Console.ReadKey();
}
}
}