【实验室笔记】C#的Socket客户端接收和发送数据

时间:2021-05-06 05:57:47

采用socket发送和接收数据的实验中,服务器采用的是网络助手作为模拟服务器端。

客户端程序流程:

应用的命名空间:

 using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Timers;

【1】首先新建一个Socket;

【2】建立ip地址应用值;

【3】Socket连接;

【4】判断连接状态;

      Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

         private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" || textBox2.Text != "")
{ IPAddress ip = IPAddress.Parse(textBox2.Text); try
{
s.Connect(ip, Convert.ToInt16(textBox1.Text));
MessageBox.Show("服务器连接中。。。");
}
catch
{
MessageBox.Show("服务器连接失败。。。");
}
try
{
if (s.Connected == true)
{
MessageBox.Show("与服务器连接成功");
aTimer.Enabled = true;
}
else
{
MessageBox.Show("与服务器连接失败");
}
}
catch
{
MessageBox.Show("检测连接状态出错");
}
}
else
{
MessageBox.Show("请输入端口号和IP地址");
} }

Socket数据的发送

         private void button2_Click(object sender, EventArgs e)
{
if (s.Connected == true)
{
try
{
string abc = textBox3.Text; s.Send(Encoding.ASCII.GetBytes(abc)); MessageBox.Show("向服务器发送:" + abc);
}
catch
{
MessageBox.Show("发送失败");
}
}
}

Socket数据接收

数据接收要交给线程去做,然后调用定时器去做,这样会防止在数据接收时,其他程序不可用的状况。

         System.Timers.Timer aTimer = new System.Timers.Timer();

         byte[] res = new byte[];

         private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
aTimer.Enabled = false;
Thread thread1 = new Thread(TimerMange);
thread1.IsBackground = true;
thread1.Start();
} void TimerMange()
{
aTimer.Elapsed += new ElapsedEventHandler(socket_rev); //定时事件的方法
aTimer.Interval = ;
} private void socket_rev(object sender, EventArgs e)
{
int receiveLength = s.Receive(res, res.Length, SocketFlags.None); if (receiveLength > )
{
textBox4.Text = Encoding.ASCII.GetString(res, , receiveLength);
string abc = "HaveReceive";
s.Send(Encoding.ASCII.GetBytes(abc));
}
}