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>,在出现比 ...
随机推荐
- 使用startCoroutine制定倒计时
使用startCoroutine制定倒计时 using UnityEngine; using System.Collections; public class TimerCoroutine : Mon ...
- sqlserver 连不上的问题
tcp ip 属性 ipall 属性改为1433
- 如何用eclipse搭建Android的开发环境
l开发主要应用Eclipse 3.7版本. l辅助工具为jdk.Androidsdk Android环境搭建 –1.1.JDK安装 –1.2.Eclipse安装 –1.3.Android SDK安 ...
- Unity3D 之NGUI各种脚本及应用
这里来介绍一下NGUI的各种脚本的作用,以便以后需要某种效果的时候,去添加相应的脚本去实现效果 UIButton --> 按钮脚本 UIPanel --> 面板脚本 UIToggle ...
- C#中params使用
1.参数被params修饰即为可变参数,params只能修饰一维数组. 2.给可变参数赋值的时候,可以直接传递数组的元素. 3.在调用的时候,会自动将这些元素封装为一个数组,并将数组传递. 4.可变参 ...
- 20151216JqueryUI---dialog代码备份
$(function () { $('#search_button').button(); /*$('#reg').dialog({ focus:function(e,ui){ alert('注册') ...
- poj1182 食物链(种类并查集)详解
poj 1182 http://poj.org/problem?id=1182 分析:这个题大意说的非常清楚了,就是求出假话的个数,题目中给的假话要求有三个 ① 当前的话与前面的某些真的话冲突,是 ...
- windows访问linux共享
1. 安装samba yum install samba 2. 配置samba配置文件,添加共享文件夹 vim /etc/samba/smb.conf 3. 关闭selinux vi /etc ...
- tableview刷新某个区域(section)或者某一行(row)
//一个section刷新 NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2]; [tableview reloadSections:in ...
- Objective-C 中的方法回掉
Objective-C 中的方法回掉 Objective-C 中的方法调用 OC 类似C+,避免不了的内部的各种通信手段,函数调用,变量传递等,避免不了各种回掉等. 一.class直接调用 或者 o ...