使用C#的Socket開(kāi)發(fā)網(wǎng)絡(luò)版來(lái)電管理軟件 |
chen在2009/9/7發(fā)表,被瀏覽4372次
|
適合對(duì)象:記得來(lái)電顯示管理器的網(wǎng)絡(luò)版 開(kāi)發(fā)環(huán)境:Visual C# 下載范例:6.zip ( 46.13K ) [ 2009-09-07 ] 使用環(huán)境:需要來(lái)電監(jiān)聽(tīng)服務(wù)程序TeleListen.exe(點(diǎn)擊下載) 相關(guān)連接:來(lái)電管理器服務(wù)程序
 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; namespace _ { public partial class Form1 : Form { static string strReceived=""; static string server; static int port; static Socket socketTele; static Thread thrListen; public Form1() { InitializeComponent(); } private static Socket ConnectSocket() { Socket socket = null; //實(shí)例化Socket對(duì)象,并初始化為空 IPHostEntry iphostentry = null; //實(shí)例化IPHostEntry對(duì)象,并初始化為空 iphostentry = Dns.GetHostEntry(server); //獲得主機(jī)信息 //循環(huán)遍歷得到的IP地址列表 foreach (IPAddress address in iphostentry.AddressList) { //使用指定的IP地址和端口號(hào)實(shí)例化IPEndPoint對(duì)象 IPEndPoint IPEPoint = new IPEndPoint(address, port); //使用Socket的構(gòu)造函數(shù)實(shí)例化一個(gè)Socket對(duì)象,以便用來(lái)連接遠(yuǎn)程主機(jī) Socket newSocket = new Socket(IPEPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); newSocket.Connect(IPEPoint); //調(diào)用Connect方法連接遠(yuǎn)程主機(jī) if (newSocket.Connected) //判斷遠(yuǎn)程連接是否連接 { socket = newSocket; break; } else { continue; } } return socket; } //接收Socket服務(wù)發(fā)送的內(nèi)容 private static string SocketReceive() { Byte[] btReceived = new Byte[256]; int intContent = 0; if (socketTele == null) return "Not connected"; do { Application.DoEvents(); //從綁定的Socket接收數(shù)據(jù) intContent = socketTele.Receive(btReceived, btReceived.Length, 0); //將接收到的數(shù)據(jù)轉(zhuǎn)換為字符串類型 strReceived += Encoding.ASCII.GetString(btReceived, 0, intContent) + "\n"; } while (intContent > 0); return strReceived; } //使用線程監(jiān)聽(tīng)Socket public static void ListenThread() { //調(diào)用自定義方法SocketSendReceive獲取指定主機(jī)的主頁(yè)面內(nèi)容 string strContent = SocketReceive(); MessageBox.Show(strContent); } //啟動(dòng)線程 private void button1_Click(object sender, EventArgs e) { server = textBox1.Text; //指定主機(jī)名 port = Convert.ToInt32(textBox2.Text); //指定端口號(hào) socketTele = ConnectSocket(); if (socketTele == null) { strReceived = "連接失敗!\n"; return; } thrListen = new Thread(new ThreadStart(ListenThread)); thrListen.Start(); } //關(guān)閉Socket連接 private void button2_Click(object sender, EventArgs e) { if (socketTele != null) { socketTele.Close(); thrListen.Abort(); } } //顯示接收的內(nèi)容 private void timer1_Tick(object sender, EventArgs e) { int i; if (strReceived.Length > 0) { i = strReceived.IndexOf("\n"); while (i > 0) { listBox1.Items.Add(strReceived.Substring(0, i+1)); strReceived=strReceived.Remove(0, i+1); i = strReceived.IndexOf("\n"); } } } } }
|
|
|
|