C# 简单Tcp通信demo
Client 代码
private void btnSend_Click(object sender, EventArgs e)
{
TcpClient tcpClient = new TcpClient(txthost.Text, Int32.Parse(txtport.Text)); //创建tcp客户端
NetworkStream ns = tcpClient.GetStream(); //创建网络流
FileStream fs = File.Open("..\\..\\Form1.cs", FileMode.Open); //打开文件
int data = fs.ReadByte();
while(data!=-1)
{
ns.WriteByte((byte)data);
data = fs.ReadByte(); //读写文件操作
}
fs.Close();
ns.Close();
tcpClient.Close();
}
Receive端代码
public Form1()
{
InitializeComponent();
//通过线程 获取网络 tcp监听获取网络数据
new Thread(()=>{
IPAddress loacaladdr = IPAddress.Parse("127.0.0.1");
Int32 port = 2112;
TcpListener tcplistener = new TcpListener(loacaladdr, port);
tcplistener.Start();
TcpClient tcpClient = tcplistener.AcceptTcpClient();
NetworkStream ns = tcpClient.GetStream();
StreamReader sr = new StreamReader(ns);
string result = sr.ReadToEnd();
//this.Invoke(new UpdateDisplayDelegate(DisPlay), new object[] { result });
this.Invoke((MethodInvoker)delegate
{
txtDisplay.Text = result;
});
}).Start();
}