采用socket发送和接收数据的实验中,服务器采用的是网络助手作为模拟服务器端。
客户端程序流程:
应用的命名空间:
1 using System.Net; 2 using System.Net.Sockets; 3 using System.Threading; 4 using System.Timers;
【1】首先新建一个Socket;
【2】建立ip地址应用值;
【3】Socket连接;
【4】判断连接状态;
1 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 2
3 private void button1_Click(object sender, EventArgs e) 4 { 5 if (textBox1.Text != "" || textBox2.Text != "") 6 { 7
8 IPAddress ip = IPAddress.Parse(textBox2.Text); 9
10 try
11 { 12 s.Connect(ip, Convert.ToInt16(textBox1.Text)); 13 MessageBox.Show("服务器连接中。。。"); 14 } 15 catch
16 { 17 MessageBox.Show("服务器连接失败。。。"); 18 } 19 try
20 { 21 if (s.Connected == true) 22 { 23 MessageBox.Show("与服务器连接成功"); 24 aTimer.Enabled = true; 25 } 26 else
27 { 28 MessageBox.Show("与服务器连接失败"); 29 } 30 } 31 catch
32 { 33 MessageBox.Show("检测连接状态出错"); 34 } 35 } 36 else
37 { 38 MessageBox.Show("请输入端口号和IP地址"); 39 } 40
41 }
Socket数据的发送
1 private void button2_Click(object sender, EventArgs e) 2 { 3 if (s.Connected == true) 4 { 5 try
6 { 7 string abc = textBox3.Text; 8
9 s.Send(Encoding.ASCII.GetBytes(abc)); 10
11 MessageBox.Show("向服务器发送:" + abc); 12 } 13 catch
14 { 15 MessageBox.Show("发送失败"); 16 } 17 } 18 }
Socket数据接收
数据接收要交给线程去做,然后调用定时器去做,这样会防止在数据接收时,其他程序不可用的状况。
1 System.Timers.Timer aTimer = new System.Timers.Timer(); 2
3 byte[] res = new byte[1024]; 4
5 private void Form1_Load(object sender, EventArgs e) 6 { 7 Control.CheckForIllegalCrossThreadCalls = false; 8 aTimer.Enabled = false; 9 Thread thread1 = new Thread(TimerMange); 10 thread1.IsBackground = true; 11 thread1.Start(); 12 } 13
14 void TimerMange() 15 { 16 aTimer.Elapsed += new ElapsedEventHandler(socket_rev); //定时事件的方法
17 aTimer.Interval = 100; 18 } 19
20 private void socket_rev(object sender, EventArgs e) 21 { 22 int receiveLength = s.Receive(res, res.Length, SocketFlags.None); 23
24 if (receiveLength > 0) 25 { 26 textBox4.Text = Encoding.ASCII.GetString(res, 0, receiveLength); 27 string abc = "HaveReceive"; 28 s.Send(Encoding.ASCII.GetBytes(abc)); 29 } 30 }