C# socket编程 异步服务端 同步客户端 收藏
异步服务端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace Gps_GateWay
...{
public partial class Form1 : Form
...{
public static ManualResetEvent allDone = new ManualResetEvent(false);
private Thread th;
private bool listenerRun = true;
Socket listener;
private const int maxsocket = 10;
public Form1()
...{
InitializeComponent();
}
private IPAddress GetLocalIP()
...{
IPHostEntry iphostentry = Dns.GetHostByName(Dns.GetHostName());
return iphostentry.AddressList[0];
}
private void Listen()
...{
try
...{
int port = int.Parse(txtPort.Text);
IPAddress ipaddress = GetLocalIP();
IPEndPoint ipendpoint = new IPEndPoint(ipaddress, port);
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(ipendpoint);
listener.Listen(50);
while (listenerRun)
...{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallBack), listener);
allDone.WaitOne();
}
}
catch (Exception Err)
...{
MessageBox.Show(Err.Message);
}
}
private delegate void GetLstControl(string hostname, string remoteip, string remoteport);
private void GetLstStr(string hostname, string remoteip, string remoteport)
...{
lstIP.Items.Add("[" + hostname + "] " + remoteip + ":" + remoteport);
}
private void AcceptCallBack(IAsyncResult ar)
...{
try
...{
allDone.Set();
Socket sok = (Socket)ar.AsyncState;
Socket client = sok.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = client;
EndPoint remoteendpoint = client.RemoteEndPoint;
IPEndPoint ipendpoint = (IPEndPoint)remoteendpoint;
string remoteip = ipendpoint.Address.ToString();
string remoteport = ipendpoint.Port.ToString();
IPHostEntry iphostentry = Dns.GetHostByAddress(ipendpoint.Address);
string hostname = iphostentry.HostName;
GetLstControl getlst = new GetLstControl(GetLstStr);
this.BeginInvoke(getlst,new object[]...{hostname,remoteip,remoteport});
client.BeginReceive(state.buffer, 0,StateObject.BufferSize,0, new AsyncCallback(ReadCallBack), state);
}
catch (Exception Err)
...{
// MessageBox.Show(Err.Message);
}
}
private delegate void GetRchControl(string str);
private void GetRchMsg(string str)
...{
rchMsg.AppendText(str);
}
private void ReadCallBack(IAsyncResult ar)
...{
try
...{
StateObject state = (StateObject)ar.AsyncState;
Socket hander = state.workSocket;
int readbyte = hander.EndReceive(ar);
if (readbyte > 0)
...{
string strcontent = "";
string str_msg = "";
string strmsg = "";
strmsg=Encoding.BigEndianUnicode.GetString(state.buffer, 0, readbyte);
state.sb.Length = 0;
state.sb.Append(strmsg);
strcontent = state.sb.ToString() + " ";
EndPoint remoteendpoint = hander.RemoteEndPoint;
IPEndPoint ipendpoint = (IPEndPoint)remoteendpoint;
string remoteip = ipendpoint.Address.ToString();
string remoteport = ipendpoint.Port.ToString();
IPHostEntry iphostentry = Dns.GetHostByAddress(ipendpoint.Address);
string hostname = iphostentry.HostName;
string time = DateTime.Now.ToString();
str_msg = "(" + time + ") " + hostname + ":" + strcontent + " ";
GetRchControl getrch = new GetRchControl(GetRchMsg);
this.BeginInvoke(getrch, new object[] ...{ str_msg });
byte[] byteData = Encoding.BigEndianUnicode.GetBytes("(" + time + ") " + "信息发送成功 ");
hander.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), hander);
hander.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallBack), state);
}
}
catch (Exception Err)
...{
MessageBox.Show(Err.Message);
}
}
private void Send(Socket handler, String data)
...{
byte[] byteData = Encoding.BigEndianUnicode.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
}
private void SendCallback(IAsyncResult ar)
...{
try
...{
//Socket handler = (Socket)ar.AsyncState;
//int bytesSent = handler.EndSend(ar);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}
catch (Exception Err)
...{
MessageBox.Show(Err.Message);
}
}
private void button1_Click(object sender, EventArgs e)
...{
th = new Thread(new ThreadStart(Listen));
th.Start();
}
}
public class StateObject
...{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
}
下载:http://d.download.csdn.net/down/297579/lem12 同步客户端
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 GPs_Client_Test
...{
public partial class Form1 : Form
...{
private Socket sok;
private IPAddress ipaddress;
private IPEndPoint ipendpoint;
public Form1()
...{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
...{
try
...{
Thread th = new Thread(new ThreadStart(Get_TEst));
th.Start();
}
catch (Exception Err)
...{
MessageBox.Show(Err.Message);
}
}
private void GetStr(string str1)
...{
revicestr.AppendText(str1 + " ");
}
private delegate void GetControl(string str1);
private void Get_TEst()
...{
try
...{
ipaddress = IPAddress.Parse(textBox1.Text);
int port = int.Parse(textBox2.Text);
ipendpoint = new IPEndPoint(ipaddress, port);
sok = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sok.Connect(ipendpoint);
while (true)
...{
byte[] byt = new byte[1024];
string str = "";
sok.Receive(byt, byt.Length, 0);
str = Encoding.BigEndianUnicode.GetString(byt);
GetControl getcon = new GetControl(GetStr);
this.BeginInvoke(getcon, new object[] ...{ str});
}
}
catch (Exception Err)
...{
MessageBox.Show(Err.Message);
}
}
private void button2_Click(object sender, EventArgs e)
...{
try
...{
byte[] sendbyte = new byte[1024];
string str = richTextBox2.Text;
sendbyte = Encoding.BigEndianUnicode.GetBytes(str);
sok.Send(sendbyte);
}
catch (Exception Err)
...{
MessageBox.Show(Err.Message);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
...{
try
...{
if (sok != null)
...{
sok.Close();
}
}
catch (Exception Err)
...{
}
}
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/lem12/archive/2007/11/28/1905732.aspx