我已經做了一個簡單的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服務那樣使用? –