1. socket同步通讯:
Socket m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_socket.Connect(m_ipEnd);
m_socket.Send(buf_send, (int)m_len, SocketFlags.None);
m_socket.Receive(buf_recv, (int)m_len, SocketFlags.None);
m_socket.Close();
2. socket异步通讯
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.Collections;
namespace WinSocketAsync
{
public partial class FormMain : Form
{
public Socket m_socket;
public IPEndPoint m_iep;
Queue m_qSend = new Queue();
Queue m_qRecv = new Queue();
int m_interval; //发送间隔
int m_DataLen; //数据长度
ulong m_curSendCount; //当前发送次数
ulong m_curRecvCount; //当前接收次数
ulong m_curSendBit; //当前发送位数
ulong m_curRecvBit; //当前接收位数
ulong m_curRightBit; //当前正确位数
ulong m_curErrorBit; //当前错误位数
byte[][] m_senddata; //发送的数据包
delegate void DGTextBox(string str);
delegate void DGButton(bool b);
public class StateObject : Object
{
public Socket socket;
public byte[] buffer;
}
public FormMain()
{
InitializeComponent();
//m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName. )
}
private void FormMain_Load(object sender, EventArgs e)
{
TCurTime_Tick(sender, e);
m_interval = int.Parse(TBinterval.Text.Trim());
m_DataLen = int.Parse(TBDataLen.Text.Trim());
m_senddata = new byte[256][];
Random rd = new Random();
for (int i = 0; i < 256; i++)
{
m_senddata[i] = new byte[m_DataLen];
for (int j = 0; j < m_DataLen; j++)
{
m_senddata[i][j] = (byte)rd.Next(1, 255);
}
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (m_socket == null)
{
return;
}
if (m_socket.Connected)
{
m_socket.Shutdown(SocketShutdown.Receive);
m_socket.Close();
}
}
private void TBinterval_TextChanged(object sender, EventArgs e)