程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> Socket編程二

Socket編程二

編輯:關於.NET

客戶端

using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Net;//使用IPAredd類,IPHostEntry類
namespace QQ
{
public partial class Tcpclient : Form
{
private StreamWriter write;
private NetworkStream stream;
private TcpClient tcpclient;
public Tcpclient()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
tcpclient = new TcpClient(AddressFamily.InterNetwork);
tcpclient.Connect("127.0.0.1",8000);
stream = tcpclient.GetStream();
write = new StreamWriter(stream);
write.WriteLine(this.textBox1.Text);
write.Flush();
}
catch
{
}
}
}
}

服務器端

using System.Net.Sockets;//使用了TcpListen類
using System.Threading;//使用到了線程
using System.IO;//使用到了StreamReader類
using System.Net;
namespace QQ
{
public partial class Tcpserver : Form
{
int port = 8000;//定義偵聽端口號
private Thread threadRead; //創建線程,用以偵聽端口號,接受信息
private TcpListener tcpListen;//偵聽端口號
private bool blistener = true;
private NetworkStream stream;
private StreamReader read;
private TcpClient client;
private delegate void listbox_show(string str);
listbox_show listboxshow;
public Tcpserver()
{
InitializeComponent();
listboxshow = new listbox_show(show);
}
private void Listen()
{
try
{
tcpListen = new TcpListener(8000); //用8000端口來初始化TcpListener實例
tcpListen.Start();//開始監聽
client = tcpListen.AcceptTcpClient();//通過tcp連接請求
stream = client.GetStream(); //獲取基本的流
read = new StreamReader(stream); //用得到的網絡基礎數據流來初始化StreamReader實例
while (blistener)
{
string message = read.ReadLine();//從網絡基礎數據流中讀取一行數據
if (message == "STOP")
{
tcpListen.Stop();//關閉偵聽
stream.Close();//釋放資源
read.Close();
threadRead.Abort();
return;
}
string sTime = DateTime.Now.ToShortDateString();
listBox1.Invoke(listboxshow,sTime + " " + message);
}
}
catch (System.Security.SecurityException)
{
MessageBox.Show("偵聽失敗!","錯誤");
}
}
private void show(string str)
{
this.listBox1.Items.Add(str);
}
//開始偵聽
private void button1_Click(object sender, EventArgs e)
{
threadRead = new Thread(new ThreadStart(Listen));
threadRead.Start();
this.button1.Enabled = false;
}
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved