using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text; namespace WebSocket
{
public partial class WebSocketTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SocketServer socket = new SocketServer(, "192.168.88.196", TextBox1);
//启动线程
Thread thread = new Thread(new ThreadStart(socket.beginListen));
thread.Start();
// 在应用程序启动时运行的代码
//(new System.Threading.Thread(new System.Threading.ThreadStart(new Class1().CreatSocket))).Start();//开辟一个新线程
} }
protected void Button1_Click(object sender, EventArgs e)
{
Socketclient client = new Socketclient(TextBox2, TextBox3);
client.StartClient(); } } public class Socketclient
{
TextBox txt;
TextBox send_txt;
public Socketclient(TextBox txt, TextBox send_txt)
{
this.txt = txt;
this.send_txt = send_txt;
}
public void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[]; // Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, );
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
// Console.WriteLine("Socket connected to {0}",sender.RemoteEndPoint.ToString());
txt.Text += "\r\n" + sender.RemoteEndPoint.ToString() + "\r\n";
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(send_txt.Text + "<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
//Console.WriteLine("Echoed test = {0}",Encoding.ASCII.GetString(bytes,0,bytesRec));
txt.Text += "\r\n" + Encoding.ASCII.GetString(bytes, , bytesRec) + "\r\n";//接收远程服务器信息 // Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
// Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
txt.Text += "\r\n" + ane.ToString() + "\r\n";
}
catch (SocketException se)
{
// Console.WriteLine("SocketException : {0}",se.ToString());
txt.Text += "\r\n" + se.ToString() + "\r\n";
}
catch (Exception e)
{
// Console.WriteLine("Unexpected exception : {0}", e.ToString());
txt.Text += "\r\n" + e.ToString() + "\r\n";
}
}
catch (Exception e)
{
// Console.WriteLine( e.ToString());
txt.Text += "\r\n" + e.ToString() + "\r\n";
}
}
}
public class SocketServer { int port; //端口
string host;//ip地址
TextBox txt;
/// <summary>
/// 构造涵数
/// </summary>
/// <param name="ports">端口号</param>
public SocketServer(int ports, string host,TextBox txt)
{
this.port=ports;
this.host = host;
this.txt = txt;
}
//开始监听
public void beginListen(){
try
{
IPAddress ip = IPAddress.Parse(host);//把ip地址字符串转换为IPAddress类型的实例
IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint类的新实例
///创建socket并开始监听
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket对像,如果用udp协议,则要用SocketType.Dgram类型的套接字
s.Bind(ipe);//绑定EndPoint对像(端口和ip地址)
s.Listen();//开始监听
txt.Text += "等待客户端连接";
// Console.WriteLine("等待客户端连接");
//定义循环,以便可以简历多次连接
while (true)
{
Socket temp = s.Accept();//为新建连接创建新的socket
while (true)
{
string recvStr = "";
byte[] recvBytes = new byte[];
int bytes;
bytes = temp.Receive(recvBytes, recvBytes.Length, );//从客户端接受信息
recvStr += Encoding.ASCII.GetString(recvBytes, , bytes);
txt.Text += "\r\n" + recvStr + "\r\n";
if (recvStr.IndexOf("<EOF>") > -)
{
break;
}
}
//给client端返回信息
// Console.WriteLine("server get message:{0}", recvStr);//把客户端传来的信息显示出来 string sendStr = "jpeg upload OK";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
temp.Send(bs, bs.Length, );//返回信息给客户端
temp.Shutdown(SocketShutdown.Both);
temp.Close(); }
}
catch (Exception ex)
{
string str = ex.ToString();
txt.Text += "\r\n" + str + "\r\n";
}
}
}
}
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Height="206px" TextMode="MultiLine" Width="700px" ></asp:TextBox>
<hr />
<asp:TextBox ID="TextBox2" runat="server" Height="197px" TextMode="MultiLine" Width="376px"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server" Height="119px" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Height="52px" OnClick="Button1_Click" Text="SEND" Width="138px" />
</div>
</form>
</body>


asp.net中Web使用Socket的更多相关文章

  1. Asp.net中web.config配置文件详解(一)

    本文摘自Asp.net中web.config配置文件详解 web.config是一个XML文件,用来储存Asp.NET Web应用程序的配置信息,包括数据库连接字符.身份安全验证等,可以出现在Asp. ...

  2. Asp.net中web.config配置文件详解(二)

    摘自http://blog.csdn.net/hbqhdlc/article/details/8155668 近日正在看Asp.net,看到Web.config有很不清楚之处,特意从网络.MSDN搜集 ...

  3. asp.net中web.config配置节点大全详解

    最近网上找了一些关于Web.config配置节点的文章,发现很多都写的都比较零散,而且很少有说明各个配置节点的作用和用法.搜索了一下发现有一篇写的不错,这里引用一下 原文地址 http://www.c ...

  4. ASP.NET中Web DataGrid的使用指南

    DataGrid/DataList在ASP.NET非常重要,凡显示Table类型的数据,大多会使用这两个控件. 一.方法 1.DataBind很简单.最常用的方法.绑定数据用.需要注意的只有一点:执行 ...

  5. asp.net中web.config配置节点大全详解【转】

    web.config 文件查找规则: (1)如果在当前页面所在目录下存在web.config文件,查看是否存在所要查找的结点名称,如果存在返回结果并停止查找. (2)如果当前页面所在目录下不存在web ...

  6. Asp.net中web.config配置文件详解

    Web.config文件是一个XML文本文件,它用来储存 ASP.NET Web 应用程序的配置信息(如最常用的设置ASP.NET Web 应用程序的身份验证方式),它可以出现在应用程序的每一个目录中 ...

  7. [转载].NET ASP.NET 中web窗体(.aspx)利用ajax实现局部刷新

    之前开发的一套系统中用到了大量的 checkboxList 控件,但是每次选定之后都会刷新整个页面,用户体验很差,百度了之后查到这篇文章,尝试了一下可以实现,所以转载了过来,记录一下,也给其他有相同困 ...

  8. 聊聊asp.net中Web Api的使用

    扯淡 随着app应用的崛起,后端服务开发的也越来越多,除了很多优秀的nodejs框架之外,微软当然也会在这个方面提供更便捷的开发方式.这是微软一贯的作风,如果从开发的便捷性来说的话微软是当之无愧的老大 ...

  9. 在asp.net 中web.config配置错误页

    每当用户访问错误页面时,会出现不友好的错误页面,所以为了防止这种不友好,我们在web.config中的<system.web>节点下配置 <customErrors>,在出现比 ...

随机推荐

  1. How does CCFileUTils::fullPathForFilename work

    OverView The purpose of this document is show you how does function CCFileUtils::fullPathForFilename ...

  2. c指针与数组,传参问题,指针数组与数组指针的区别,二维数组动态内存分配

    一 数组的结构:顺序存储,看谭浩强中的图,牢记 1.数组名指代一种数据结构:数组 现在可以解释为什么第1个程序第6行的输出为10的问题,根据结论1,数组名str的内涵为一种数据结构,即一个长度为10的 ...

  3. 通过ApplicationContextAwareSpring实现手工加载配置的javabean

    在做一个多线程的数据采集器实现的过程中,由于框架是集成srping,因此希望统一使用原有的数据库配置信息,但是需要手工获取数据库配置bean.我们可以通过继承ApplicationContextAwa ...

  4. Nginx高性能服务器安装、配置、运维 (2) —— Nginx安装

    三.Nginx 安装 使用SecureCRT以Root身份登录阿里云,在安装Nginx前先做好阿里云磁盘挂载 -------------- 挂载磁盘 -------------- 1.df -h #显 ...

  5. 获取当前时间日期并格式化--JS

    工作当中,总是遇到很多觉得不错的JS脚本.现在觉得还是找个地方记录下来,以后可以随时查看. /** *获取当前时间日期并格式化 */ function getNowDate(){ var mydate ...

  6. SQL Server 2008导入、导出数据库

    SQL Server 2008数据库的导入.导出和Mysql的导出还有一定的区别,刚开始的时候完全摸不到方向,利用Microsoft SQL Server Management Studio进行导入. ...

  7. JAVA Web.xml 加载顺序

    web.xml加载过程(步骤): 1.启动WEB项目的时候,容器(如:Tomcat)会去读它的配置文件web.xml.读两个节点: <listener></listener> ...

  8. poj2299 二分思想

    poj2299   http://poj.org/problem?id=2299题意: 一个含有n个数的数组, 每次只能交换相邻的两个数, 求最少操作多少次可以使该数组变成一个有序数组(从小到大).  ...

  9. Android Activity的生命周期详解

    应用程序中,一个Activity通常就是一个单独的屏幕,它上面可以显示一些控件也可以监听并处理用户的事件做出响应. Activity之间通过Intent进行通信.在Intent 的描述结构中,有两个最 ...

  10. Android在onCreate()中获得控件尺寸

    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceSt ...