C# TCP协议的使用步骤
8 个月前
1.代码展示:
先上一波代码看看基本的使用步骤:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace 例4_TcpClient与Listener的界面版
public partial class Form1 : Form
public Form1()
InitializeComponent();
//private void btnServer_Click(object sender, EventArgs e)
private async void btnServer_Click(object sender, EventArgs e)
TcpListener listener = new TcpListener(IPAddress.Parse( "127.0.0.1"),4001);
listener.Start();
//这是一个阻断的方法,运行到此就不再向下运行了,所以把客户端与服务器端放在一个程序下是不行的.可以采用多线程方法进行处理.
//TcpClient tc = listener.AcceptTcpClient();
TcpClient tc = await listener.AcceptTcpClientAsync(); //这是一个异步方法,frameWork4.5以上使用
NetworkStream stm = tc.GetStream();
byte[] readBuf = new byte[50];
stm.Read(readBuf, 0, 50);
txtMess.Text = Encoding.ASCII.GetString(readBuf);
//stm.Close();
catch(Exception ex)
MessageBox.Show("出现问题:" + ex.Message.ToString());
private void btnClient_Click(object sender, EventArgs e)
TcpClient newclient = new TcpClient();
newclient.Connect("localhost",4001);
NetworkStream stm = newclient.GetStream();
byte[] sendbyte = Encoding.ASCII.GetBytes("data is coming here!");
stm.Write(sendbyte,0,sendbyte.Length);
//newclient.Close();
catch (Exception ex)