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

socket編程一

編輯:關於.NET

准備弄個.net的Socket系列,先弄個簡單的

客戶端代碼

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class net_client : Form
{
public net_client()
{
InitializeComponent();
}
private void btn_send_Click(object sender, EventArgs e)
{
Socket socket;
//提供網際協議的ip地址
IPAddress HostIP = IPAddress.Parse("127.0.0.1");
//將網絡端點表示為ip地址和端口號
IPEndPoint point;
try
{
point = new IPEndPoint(HostIP, Int32.Parse("1571"));
//AddressFamily指定Socket的尋址方式
//指定Socket的協議類型ProtocolType.Tcp
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(point);
//向服務器發送數據
byte[] sendByte = new byte[64];
string sendStr = this.textBox1.Text + "\r\n";
sendByte = Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());
socket.Send(sendByte, sendByte.Length, 0);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

服務器端的代碼

using System;
using System.Text;
using System.Net;
using System.Threading;
using System.Diagnostics;
using System.Net.Sockets;
namespace WindowsApplication1
{
public partial class net_server : Form
{
public net_server()
{
InitializeComponent();
}
//聲明委托
delegate void SetTextCallback(string text);
private void SetText(string text)
{
textBox1.AppendText(text + "\r\n");
}
//提供網際協議(IP)地址IPAddress
IPAddress HostIP = IPAddress.Parse("127.0.0.1");
//將網絡端點表示為IP地址和端口號
IPEndPoint point;
//定義兩個套接字
Socket socket;
Socket acceptedSocket;
//開啟接受套接字的服務
private void button1_Click(object sender, EventArgs e)
{
try
{
point = new IPEndPoint(HostIP, Int32.Parse("1571"));
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(point);
socket.Listen(50);
//acceptedSocket = socket.Accept();
Thread thread = new Thread(new ThreadStart(Process));
thread.Start();
}
catch (Exception ey)
{
MessageBox.Show(ey.Message);
}
}
//要專門用一個線程來accept 一個線程來receive數據
private void Process()
{
acceptedSocket = socket.Accept();
if (acceptedSocket.Connected)
{
byte[] receiveByte = new byte[64];
acceptedSocket.Receive(receiveByte, receiveByte.Length, 0);
string strInfo = Encoding.BigEndianUnicode.GetString(receiveByte);
//在擁有控件的基礎窗口句柄的線程上,用指定的參數列表執行指定的委托
this.Invoke(new SetTextCallback(SetText), new object[] { strInfo });
}
else
{
this.textBox1.Text = "還沒有信息";
}
}
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved