我正在尝试从 asp web 应用程序连接到 tcp 服务器。我在 C# 中使用应用程序完成了此操作,现在我想看看它是否可以在 Web 浏览器中运行。
我的代码是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace TcpWebClient
{
public partial class _Default : System.Web.UI.Page
{
private byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(
IPAddress.Parse("192.168.1.20"), 12000);
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
server.Connect(ipep);
}
catch (SocketException)
{
}
}
protected void Button2_Click(object sender, EventArgs e)
{
NetworkStream ns = new NetworkStream(server);
if (ns.CanWrite)
{
ns.Write(Encoding.ASCII.GetBytes("DI"), 0, 2);
ns.Flush();
}
else
{
}
TextBox1.Text = null;
TextBox1.Text = Encoding.ASCII.GetString(data, 0, ns.Read(data, 0, data.Length));
}
}
}
什么工作?:我连接到 tcp 服务器。但是当我想发送和接收一些数据时,我遇到了错误:
IOException was unhandled by user code and something like this: Operation is not supported on connected sockets (don't know if my translation to english is ok).
我做错了什么?
System.dll 中出现“System.IO.IOException”类型的第一次机会异常
编辑:
像这样的东西正在工作..但是我需要重新连接到服务器的每个计时器滴答声..是否可以建立一个连接,然后每个计时器滴答声读取/发送数据而不重新连接?
protected void Timer1_Tick(object sender, EventArgs e)
{
server.Connect(ipep);
NetworkStream stream = new NetworkStream(server);
Byte[] data = System.Text.Encoding.ASCII.GetBytes("data");
stream.Write(data, 0, data.Length);
data = new Byte[256];
Int32 bytes = stream.Read(data, 0, 8);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
TextBox1.Text = responseData;
server.Close();
}