c#简单的socket通讯demo
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
namespace ClientSocket
{
class Program
{
private static Socket ServersClientSocket;//服务端得到的客户端的SOCKET
private static Socket ClientSocket;//客户端Socket
private static object lockHelper = new object();
/// <summary>
/// 开启服务端
/// </summary>
private static void StartAccept()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.3.18"), 1005);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//下一句 设置SOCKET允许多个SOCKET访问同一个本地IP地址和端口号
//server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
server.Bind(ipep);
server.Listen(60);//非阻塞方法
while (true)
{
try
{
Console.WriteLine("server:being listen");
ServersClientSocket = server.Accept();//阻塞方法
Console.WriteLine("server:accept one link");
Thread t = new Thread(new ThreadStart(StartReceive));
t.Start();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
/// <summary>
/// 服务端开始接收数据
/// </summary>
private static void StartReceive()
{
IPEndPoint clientep = (IPEndPoint)ServersClientSocket.RemoteEndPoint;
while (true)
{
var message = RecevieMessage();
Console.WriteLine("server:the client send message is:\n" + message);
}
}
/// <summary>
/// 客户端开始连接服务端
/// </summary>
private static void StartConnect()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.3.18"), 1005);
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ClientSocket.Connect(ipep);
while (true)
{
Console.WriteLine("client:please put your message in:");
string msg = Console.ReadLine();
byte[] data = Encoding.Unicode.GetBytes(msg);
SendMessage(data);
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="msg"></param>
private static void SendMessage(byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
ClientSocket.Send(datasize);
Console.WriteLine("发送的数据长度:" + size.ToString());
while (total < size)
{
sent = ClientSocket.Send(data, total, dataleft, SocketFlags.None);
total += sent;
dataleft -= sent;
}
}
/// <summary>
/// 接收消息
/// </summary>
private static string RecevieMessage()
{
int total = 0;
int recv;
byte[] datasize = new byte[4];
recv = ServersClientSocket.Receive(datasize, 0, 4, SocketFlags.None);
int size = BitConverter.ToInt32(datasize, 0);
int dataleft = size;
byte[] data = new byte[size];
while (total < size)
{
recv = ServersClientSocket.Receive(data, total, dataleft, SocketFlags.None);
if (recv == 0)
{
data = null;
break;
}
total += recv;
dataleft -= recv;
}
if (data == null)
{
return "error";
}
string result = Encoding.Unicode.GetString(data.Take(36).ToArray());
return result;
}
/// <summary>
/// 入口函数
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(StartAccept));
t.Start();
Thread.Sleep(3000);//等待服务线程开始工作
Thread t2 = new Thread(StartConnect);
t2.Start();
while (true)
{
ConsoleKeyInfo a = Console.ReadKey();
if (a.KeyChar == '+')
{
System.Environment.Exit(0);
}
}
}
}
}
代码中注释比较多
如果仍旧看不懂请看JimmyZhang的这篇文章
http://www.cnblogs.com/JimmyZhang/archive/2008/09/07/1286300.html
讲的很细很基础