我已经做了一个简单的ASPX页面,只有一个。此页面将通过Socket与Windows窗体应用程序建立连接。我怎样才能做一个线程客户端套接字
如何应该工作
每次我在我的点击我有一些信息传递给我的Windows窗体读,然后我会打印出来。
TCP服务器代码
public partial class PaginaTeste : System.Web.UI.Page
{
private TcpListener tcpListener;
private Thread listenThread;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnBotao_OnClick(object sender, EventArgs e)
{
this.tcpListener = new TcpListener(IPAddress.Any, 8849);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
string serverResponse = "571764;10.";
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
clientStream.Write(sendBytes, 0, sendBytes.Length);
clientStream.Flush();
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
}
tcpClient.Close();
}
客户端代码(Windows窗体)
public partial class Form1 : Form
{
TcpClient clientsocket2;
Thread thread;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button3_click(object sender, EventArgs e)
{
this.clientsocket2 = new TcpClient();
clientsocket2.Connect("server_ip", 8849);
this.thread = new Thread(new ThreadStart(this.imprimir));
this.thread.Start();
}
protected void imprimir()
{
NetworkStream serverStream = clientsocket2.GetStream();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientsocket2.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
string r = "Printing Test";
int retorno = -1;
retorno = IniciaPorta("COM7");
if (retorno == 1)
{
ConfiguraModeloImpressora(7);
BematechTX(r);
AcionaGuilhotina(1);
FechaPorta();
}
clientSocket.Close();
}
问题
如果我在点击一次,initiallize我Client Application
工作很好。在第二次点击我的时,我传递给我的Client Application
的参数返回为空。
当我在客户端应用程序
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
运行'TcpListener'(这是一个*服务器*)作为的一部分一个页面(代表请求的一部分)为我提出了一些真正的红旗......你在这里试图做什么? –
在我的服务器的特定端口中开放通信。我有一台打印机,并且我已经完成了一个Windows应用程序,通过DLL访问这台打印机。在我的Web应用程序中,我将发送数据以在本打印机中打印。所以我的Web应用程序将发送数据到Windows窗体和Windows窗体发送到打印机。我尝试过使用'ActiveX'进行通信,但是我们的Web应用程序只会在FireFox中运行。 –
为什么winform不会像REST API/web服务那样使用? –