標籤:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Net.Sockets;using System.Net;using System.Threading;namespace WindowsFormsApplication2{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } Socket s; Thread myThread; private static byte[] result = new byte[1024]; private void button1_Click(object sender, EventArgs e) { string id = this.textBox1.Text; int post = int.Parse(this.textBox2.Text); IPAddress Ips = IPAddress.Parse(id); //伺服器Ip地址 s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //建立串連 s.Bind(new IPEndPoint(Ips,post)); //綁定連接埠 s.Listen(10); //設定最大串連請求 myThread = new Thread(listen); //myThread.Start(s.RemoteEndPoint.ToString() + "串連成功"); myThread.IsBackground = true; myThread.Start(); } public void show(string msg) { textBox3.AppendText(msg + "\r\n"); } public void listen() { while (true) { Socket ceshi = s.Accept(); //接收串連並返回一個新的socket show(ceshi.RemoteEndPoint.ToString() + "串連成功"); ceshi.Send(Encoding.Default.GetBytes("呂志林是二貨")); Thread aax = new Thread(jiaoliu); aax.Start(ceshi); } } public void jiaoliu(object o) { Socket aa = o as Socket; while (true) { try { int receiveNumber = aa.Receive(result); //從Socket中讀取資料 textBox4.AppendText(aa.RemoteEndPoint.ToString() + Encoding.ASCII.GetString(result, 0, receiveNumber) + "\r\n"); } catch (Exception ex) { aa.Shutdown(SocketShutdown.Both); aa.Close(); break; } } } private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } }}
•------------------相關類--------------------------•IPAddress類:包含了一個IP地址•IPEndPoint類:包含了一對IP地址和連接埠號碼•--------------------方法們------------------------------•Socket (): 建立一個Socket•Bind(): 綁定一個本地的IP和連接埠號碼(IPEndPoint)•Listen(): 讓Socket偵聽傳入的串連嘗試,並指定偵聽隊列容量•Connect(): 初始化與另一個Socket的串連•Accept(): 接收串連並返回一個新的socket•Send(): 輸出資料到Socket•Receive(): 從Socket中讀取資料•Close(): 關閉Socket (銷毀串連)
c# socket