using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Sqlite2._0//命名空间
{
class TCP
{
Socket socketwatch;
bool Thread_Remove = false;//可以删掉
public bool Listening = false;//告诉调用已经监听上了
//创建一个新的Socket来负责通信
public Socket socketsend;
//传输并存储信息
public string Received_Text
{
private set;
get;
}
public event EventHandler OnMessageRecievedEvent;
/*放在要调用TCP类的类里面,用队列来收集收到的消息
private void Tcp_OnMessageRecievedEvent(object sender, EventArgs e)
{
lock (m_MessageQueue)
{
m_MessageQueue.Enqueue(m_Tcp.Received_Text);
}
}
*/
public int TCP_Link(int num)
{
socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建一个对方的ip变量
IPAddress ip = IPAddress.Any;
//创建一个端口号
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(num));
socketwatch.Bind(point);
socketwatch.Listen(10);
//创建线程进行监听
Thread thread1 = new Thread(Listen);
thread1.IsBackground = true;
if (Thread_Remove == false)
{
thread1.Start(socketwatch);
return 1;
}
else
{
thread1.Abort();
return 0;
}
}
public void Listen(object o)
{
//参数o转换为socket类型
socketwatch = o as Socket;
while (true)
{
socketsend = socketwatch.Accept();
Thread thread2 = new Thread(Received); //创建线程进行接收
thread2.IsBackground = true;
if (Thread_Remove == false)
{
thread2.Start(socketsend);
Listening = true;
}
else
{
thread2.Abort();
}
}
}
public void Received(object o)
{
socketsend = o as Socket;
try
{
while (true)
{
byte[] date = new byte[1024 * 1024 * 3];
int count = socketsend.Receive(date);//得到Receive消息的字节数
Received_Text = Encoding.UTF8.GetString(date, 0, count);
if (OnMessageRecievedEvent != null)
{
OnMessageRecievedEvent(this, EventArgs.Empty);
}
}
}
catch
{
}
}
}
}
C# Socket TCP/IP 服务器代码
最新推荐文章于 2024-06-14 11:31:58 发布