1、首先添加兩個(gè)windows窗體項(xiàng)目,一個(gè)作為服務(wù)端server,一個(gè)作為客戶端Client
2、然后添加服務(wù)端代碼,添加命名空間,界面上添加TextBox控件
復(fù)制代碼 代碼如下:
using System.Net;
using System.Net.Sockets;
3、FormLoad方法添加代碼
復(fù)制代碼 代碼如下:
private void Form1_Load(object sender, EventArgs e)
{
IPEndPoint epServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7878);//IP地址和端口號(hào)
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//定義socket
socket.Bind(epServer);//綁定
socket.Listen(10);//監(jiān)聽(tīng)
socket.BeginAccept(new AsyncCallback(RecVing), socket);//異步接收,回調(diào)方法為RecVing
}
4、添加回調(diào)方法代碼
復(fù)制代碼 代碼如下:
private void RecVing(IAsyncResult rec_socket)
{
string cmdstr = "";
Socket sc = (Socket)rec_socket.AsyncState;
Socket socket = sc.EndAccept(rec_socket);
byte[] bytes = new byte[1024];
int i = socket.Receive(bytes);
cmdstr = Encoding.UTF8.GetString(bytes, 0, i);
showstrs(cmdstr);
sc.BeginAccept(new AsyncCallback(RecVing), sc);
}
5、添加showstrs方法,
定義委托private delegate void shixudong_invoke(string invokefun);
復(fù)制代碼 代碼如下:
private void showstrs(string recv_strs)
{
if (recv_strs.Length != 0)
{
if (this.InvokeRequired)
{
shixudong_invoke invoke = new shixudong_invoke(showstrs);
this.Invoke(invoke, (object)recv_strs);
}
else
{
textBox1.Text = recv_strs;
}
}
6、到此為止,服務(wù)端已經(jīng)添加完畢
7,客戶端代碼,首先跟服務(wù)端一樣,添加命名空間,在界面上添加button事件
復(fù)制代碼 代碼如下:
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint IPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7878);//IP,端口號(hào)
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.BeginConnect(IPEndPoint, new AsyncCallback(Sending), socket);//回調(diào)方法Sending
}
8、添加回調(diào)方法,代碼如下
復(fù)制代碼 代碼如下:
private void Sending(IAsyncResult rec_socket)
{
Socket socket = (Socket)rec_socket.AsyncState;
try
{
if (socket.Connected)
{
byte[] msgBuff = Encoding.UTF8.GetBytes(textBox1.Text);
socket.Send(msgBuff);
//socket.Accept();
}
else
{
Console.WriteLine("Error!", "Error!");
}
}
catch
{
Console.WriteLine("Error!", "Error!");
}
9、到此為止,客戶端代碼已經(jīng)完成,調(diào)試的時(shí)候先啟動(dòng)服務(wù)端,然后啟動(dòng)客戶端
10、運(yùn)行截圖如下,點(diǎn)擊按鈕前,在文本框中輸入shixudong
您可能感興趣的文章:- 關(guān)于B/S判斷瀏覽器斷開(kāi)的問(wèn)題討論
- 在B/S開(kāi)發(fā)中經(jīng)常用到的JavaScript技術(shù)
- b/s開(kāi)發(fā)常用javaScript技術(shù)
- Asp.net SignalR應(yīng)用并實(shí)現(xiàn)群聊功能