asp.net中Web使用Socket
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的更多相关文章
- Asp.net中web.config配置文件详解(一)
本文摘自Asp.net中web.config配置文件详解 web.config是一个XML文件,用来储存Asp.NET Web应用程序的配置信息,包括数据库连接字符.身份安全验证等,可以出现在Asp. ...
- Asp.net中web.config配置文件详解(二)
摘自http://blog.csdn.net/hbqhdlc/article/details/8155668 近日正在看Asp.net,看到Web.config有很不清楚之处,特意从网络.MSDN搜集 ...
- asp.net中web.config配置节点大全详解
最近网上找了一些关于Web.config配置节点的文章,发现很多都写的都比较零散,而且很少有说明各个配置节点的作用和用法.搜索了一下发现有一篇写的不错,这里引用一下 原文地址 http://www.c ...
- ASP.NET中Web DataGrid的使用指南
DataGrid/DataList在ASP.NET非常重要,凡显示Table类型的数据,大多会使用这两个控件. 一.方法 1.DataBind很简单.最常用的方法.绑定数据用.需要注意的只有一点:执行 ...
- asp.net中web.config配置节点大全详解【转】
web.config 文件查找规则: (1)如果在当前页面所在目录下存在web.config文件,查看是否存在所要查找的结点名称,如果存在返回结果并停止查找. (2)如果当前页面所在目录下不存在web ...
- Asp.net中web.config配置文件详解
Web.config文件是一个XML文本文件,它用来储存 ASP.NET Web 应用程序的配置信息(如最常用的设置ASP.NET Web 应用程序的身份验证方式),它可以出现在应用程序的每一个目录中 ...
- [转载].NET ASP.NET 中web窗体(.aspx)利用ajax实现局部刷新
之前开发的一套系统中用到了大量的 checkboxList 控件,但是每次选定之后都会刷新整个页面,用户体验很差,百度了之后查到这篇文章,尝试了一下可以实现,所以转载了过来,记录一下,也给其他有相同困 ...
- 聊聊asp.net中Web Api的使用
扯淡 随着app应用的崛起,后端服务开发的也越来越多,除了很多优秀的nodejs框架之外,微软当然也会在这个方面提供更便捷的开发方式.这是微软一贯的作风,如果从开发的便捷性来说的话微软是当之无愧的老大 ...
- 在asp.net 中web.config配置错误页
每当用户访问错误页面时,会出现不友好的错误页面,所以为了防止这种不友好,我们在web.config中的<system.web>节点下配置 <customErrors>,在出现比 ...
随机推荐
- cocos2d-x设计模式发掘之五:防御式编程模式
http://www.ityran.com/archives/2105 本文由子龙山人原创,泰然授权转载,转载请注明出处并通知子龙山人! 声明:防御式编程是提高程序代码质量的一种手段,它不能算是真正意 ...
- Android(java)学习笔记143:android提供打开各种文件的API接口:setDataAndType
android 打开各种文件(setDataAndType) private void openFile(File file){ Intent intent = new Intent(); inten ...
- CodeFile与CodeBehind的区别
引自:http://blog.163.com/wentworth0119@126/blog/static/17321924220122852720103/ asp.net发布项目之后 存在" ...
- 编码、解码Html代码
引用 Base64-80.js 文件 做网页的时候有时候需要把富文本框的html代码保存到数据库,那么就需要编码后保存到数据库.浏览器端或后台再解码作绑定 *编码:encode64(str) *解码: ...
- 【转】【SQLServer】SQL事务用法begin tran,commit tran和rollback tran的用法
Sql Server 2005/2008中提供了begin tran,commit tran和rollback tran来使用事务.begin tran表示开始事务, commit tran表示提交事 ...
- Maximum Product Subarray动态规划思想
该题即是昨天没有做出来的题目,想了很久,想出了一个普通的做法,提交发现超时了.思想是新建一个数组,保存每个元素与后面的元素相乘后得到的最大值,然后再在该数组中选出最大的值,返回.[笨死 发现行不通后决 ...
- stm32中.bss和.data段是在哪里初始化的
https://segmentfault.com/q/1010000004829859/a-1020000004850311 Q: STM32的启动文件startup_stm32f10x_hd.s中的 ...
- Python GUI with Tkinter (from youtube) 在youtube上能找到很多编程视频...
Python GUI with Tkinter - 1 - Introduction以上链接是一个python tkinter视频系列的第一讲的链接.虽然英语不好,但是,程序还是看得懂的(照着做就可以 ...
- Codevs 1800 假面舞会 2008年NOI全国竞赛
1800 假面舞会 2008年NOI全国竞赛 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 大师 Master 题目描述 Description 一年一度的假面舞会又开始了,栋栋也 ...
- 【CF492E】【数学】Vanya and Field
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th a ...