Asp.net中C#使用Socket发送和接收TCP数据的方法。
具体程序代码如下:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ConsoleApplication1
{
public static class SocketTest
{
private static Encoding encode = Encoding.Default;
///
/// 监听请求
///
///
public static void Listen(int port)
{
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listenSocket.Bind(new IPEndPoint(IPAddress.Any, port));
listenSocket.Listen(100);
Console.WriteLine("Listen " + port + " ...");
while (true)
{
Socket acceptSocket = listenSocket.Accept();
string receiveData = Receive(acceptSocket, 5000); //5 seconds timeout.
Console.WriteLine("Receive:" + receiveData);
acceptSocket.Send(encode.GetBytes("ok"));
DestroySocket(acceptSocket); //import
}
}
///
/// 发送数据
///
///
///
///
///
public static string Send(string host, int port, string data)
备烂 {
string result = string.Empty;
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
岁轿 clientSocket.Connect(host, port);
clientSocket.Send(encode.GetBytes(data));
Console.WriteLine("Send:" + data);
result = Receive(clientSocket, 5000 * 2); //5*2 seconds timeout.
Console.WriteLine("Receive:" + result);
DestroySocket(clientSocket);
return result;
}
///
/// 接收数据
///
///
///
///
private static string Receive(Socket socket, int timeout)
{
string result = string.Empty;
socket.ReceiveTimeout = timeout;
Listdata = new List ();
byte[] buffer = new byte[1024];
int length = 0;
try
{
while ((length = socket.Receive(buffer)) > 0)
仿雀漏 {
for (int j = 0; j < length; j++)
{
data.Add(buffer[j]);
}
if (length < buffer.Length)
{
break;
}
}
}
catch { }
if (data.Count > 0)
{
result = encode.GetString(data.ToArray(), 0, data.Count);
}
return result;
}
///
/// 销毁Socket对象
///
///
private static void DestroySocket(Socket socket)
{
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
}
socket.Close();
}
}
}
socket 接收到的一拦宽庆般是字节数组,首先要把简握字节数组转换成你需要的值,然后巧码insert到数据库就可以了
你的问题点卜早在哪里蚂弊蚂?
无非是3个步骤,
1,建立socket连接,
2,取得数据,处闷埋理数据(解析,分类,等等)
3,存数据库。
请详细描述你的问题难点,以便于解答。
既然你已经取到数据,并且把他赋值给一个变量腊尘游了。 只需在数据库兄首中建立个表。对应的存储进去啊! 如果你还不懂得怎么进行数据存储。这个是对数据库的操作。 其中 CN 代轮销表的是连接字符串
public int YG_mesageAdd(string YGname, string YGINtrodution, string iamgeAddess)
{
//设置标志位用来判断数据添加是否正确
int flage;
//实例化 sql 存储过程
SqlCommand cmd = new SqlCommand("YG_addMesage", cn);
cmd.CommandType = CommandType.StoredProcedure;
//需要添加的数据
SqlParameter[] param =
{
new SqlParameter("@YGname",YGname),
new SqlParameter("@YGINtrodution",YGINtrodution),
new SqlParameter("@iamgeAddess",iamgeAddess),
};
cmd.Parameters.AddRange(param);
// 执行操作
cn.Open();
flage = cmd.ExecuteNonQuery();
cn.Close();
return flage;
}