asp.net 用socket接收数据
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; List data = new List(); byte[] buffer = new byte[1024]; int length = 0; try { while ((length = socket.Receive(buffer)) > 0) { for (int j = 0; j 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(); } }}
说句实话,你这个需求本身在ASP.NET中是实现不了的,ASP.NET这套框架是针对HTTP请求。
如果你要进行TCP/IP编程,如果不用框架就得用Socket编程实现。如果使用框架,可以选择WCF框架,配置为TCP/IP编程模式
鉴于你已经自己实现了Socket的发送。你要找对应的接收代码,你可以去博客园中搜索socket编程即可
int port = 8080;
string host = "192.168.1.206";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
Response.Write("Conneting...\n");
c.Connect(ipe);//连接到服务器
string sendStr = " hello!This is a socket test ";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
c.Send(bs, bs.Length, 0);//发送测试信息
string recvStr = "Send Message ";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Response.Write("Client Get Message:" + recvStr );//显示服务器返回信息
c.Close();
server
string portNo = ConfigurationManager.AppSettings["PortNo"];
IPAddress ServerIp = GetServerIP();
IPEndPoint iep = new IPEndPoint(ServerIp, int.Parse(portNo));
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] byteMessage = new byte[100];
try
{
socket.Bind(iep);
}
catch (Exception ex)
{
throw ex;
}
while (flag)
{
try
{
socket.Listen(1);
Socket newSocket = socket.Accept();
newSocket.Receive(byteMessage);
string sTime = DateTime.Now.ToShortTimeString();
string msg = sTime + ":" + "Message from:";
msg += newSocket.RemoteEndPoint.ToString() + Encoding.Default.GetString(byteMessage);
byte[] bs = Encoding.ASCII.GetBytes(msg);
newSocket.Send(bs);
}
catch (SocketException ex)
{
throw ex;
}
}
这个应该不会有人白写吧,楼主碰碰运气吧。
举个例
对象名称: SocketObj
* 功能说明: 远程发送与接收
* 试用示例:
* using EC; //引用空间名
* string url = "218.75.111.74"; // URL也可以是(www.baidu.com)这种形式
* int port = 8000; //端口
* string SendStr = "domainname\n"; //组织要发送的字符串
* SendStr += "check\n";
* SendStr += "entityname:domains\n";
* SendStr += "domainname:" + this.TextBox1.Text + "\n";
* SendStr += ".\n";
* EBSocketObj o = new SocketObj(); //创建新对象
* o.Connection(url, port); //打开远程端口
* o.Send(SendStr); //发送数据
* Response.Write(o.Recev()); //接收数据
* o.Dispose(); //销毁对象
**********************************************/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace EC
{
/// <summary>
/// Socket 远程发送与接收
/// </summary>
public class SocketObj
{
private NetworkStream ns;
private bool _alreadyDispose = false;
#region 构造与释构
public EBSocketObj()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public EBSocketObj(string url, int port)
{
Connection(url, port);
}
~EBSocketObj()
{
Dispose();
}
protected virtual void Dispose(bool isDisposing)
{
if (_alreadyDispose) return;
if (isDisposing)
{
if (ns != null)
{
try
{
ns.Close();
}
catch (Exception E) { }
ns.Dispose();
}
}
_alreadyDispose = true;
}
#endregion
#region IDisposable 成员
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region 打开端口
/// <summary>
/// 打开端口
/// </summary>
/// <param name="url">URL或者:IP地址</param>
/// <param name="port"></param>
/// <returns></returns>
public virtual void Connection(string url, int port)
{
if (url == null || url == "") return;
if (port < 0) return;
if (port.ToString()==string.Empty) port = 80;
TcpClient tcp = null;
try
{
tcp = new TcpClient(url, port);
}
catch (Exception E)
{
throw new Exception("Can't connection:" + url);
}
this.ns = tcp.GetStream();
}
#endregion
#region 发送Socket
/// <summary>
/// 发送Socket
/// </summary>
/// <param name="ns"></param>
/// <param name="message"></param>
/// <returns></returns>
public virtual bool Send(string message)
{
if (ns == null) return false;
if (message == null || message == "") return false;
byte[] buf = Encoding.ASCII.GetBytes(message);
try
{
ns.Write(buf, 0, buf.Length);
}
catch (Exception E)
{
throw new Exception("Send Date Fail!");
}
return true;
}
#endregion
#region 收取信息
/// <summary>
/// 收取信息
/// </summary>
/// <param name="ns"></param>
/// <returns></returns>
public string Recev()
{
if (ns == null) return null;
byte[] buf = new byte[4096];
int length = 0;
try
{
length = ns.Read(buf, 0, buf.Length);
}
catch (Exception E)
{
throw new Exception("Receive data fail!");
}
return Encoding.ASCII.GetString(buf, 0, length);
}
#endregion
}
函界协诺: 如果是单纯的C/S软件,可以做到一个Server处理多个客户端之间的通信.但是你说是Web版的,也可以实现,但是,你需要使用WCF,Host在IIS上.
安图县19495584291: 基于asp.net平台,使用C#编程,可不可以使用socket实现客户端和服务器的通讯? - ?
函界协诺: 肯定可以, 直接建立socket...
安图县19495584291: asp.net中怎么用socket实现页面与页面之间的通讯?求一个基础的能够实现功能的代码,最好是有注释的,3Q - ?
函界协诺: 不支持 如果想在页面使用socket就要使用html5的websocket 谷歌 火狐基本都支持了
安图县19495584291: 求高手解释ASP.NET中socket和ajax的关系和区别 - ?
函界协诺: 你说的应该是webSocket ,而不是socket.这是两个概念.socket是tcp/ip协议下的东西. 你说的 webSocket 协议 和 Ajax是 Http协议讨论的东西. Ajax 是基于 JS 的xmlHttpRequest对象实现的异步刷新页面的方法.就是后台单独再启动一个请求...
安图县19495584291: 基于asp.net平台,使用C#编程,可不可以使用socket实现客户端和服务器的通讯? - ?
函界协诺: 肯定可以, 直接建立socketclient 就可以了.static int listenport = 1704; Socket clientsocket; ArrayList clients; Thread clientservice; Thread threadListen;
安图县19495584291: ASP.Net B/S通信技术?
函界协诺: 使用ASP.NET进行通信,一般不用SOCKET,完全没必要. 在.NET平台上进行开发用HTTP通信也行,用WEBSERVICE通信也行,都很常用. 在线人数的多少,主要不取决与你的通信手段,而是在于你的硬件设备以及你的系统架构设计.
安图县19495584291: 如何用一个Socket服务端去接收一个http请求 - ?
函界协诺: Java code ServerSocket serverSocket = null; int port = 8888; try { serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); } catch (IOException e) { e.printStackTrace(); System.exit(1); } while (!shutdown) { Socket socket =...
安图县19495584291: 研究tcp和socket连接php - fpm两种方式的区别 - ?
函界协诺: 物理层:HUB,网线 链路层:MAC,ARP,交换机 网络层:IP,ICMP,IGMP,路由器 传输层:TCP,UDP 会话层:HTTP,SMTP,FTP,POP3 表示层:SOAP,SSL 应用层:WebService的Method ------------------------------- Socket是对网络层操作 TcpClient是对传输层操作 ASP.NET是对会话层操作 ------------------------------- TcpClient是Socket的基础上的封装.一般的应用,用TcpClient可以了,或者使用NetStream,如果要做点高级的事情,建议用Socket做.
安图县19495584291: .net编程中,如何用socket获得局域网中其他计算机的ip以及端口??
函界协诺: 有api可用,socket是可以跨平台的.不会因为环境而改变用法,你还是看看windows下的socket编程吧.
安图县19495584291: 如何用socket访问网页 - ?
函界协诺: 你要用socket,写入流的数据就要符合HTTP协议规范,直接用HTTP连接撒. java.net.HttpURLConnection