I have an ASP .NET Web API and network printer(Epson TM-U220). I need to get the printer status on the Epson code and I just try as below. But I've only got printer-ready status. When the status is like printer busy, out of paper, door open, and others then the socket is waiting and API is crashed. Not get any response such a situation.
var server = "<Printer IP Address>";
Socket clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
clientSocket.NoDelay = true;
IPAddress ip = IPAddress.Parse(server);
IPEndPoint ipep = new IPEndPoint(ip, 9100);
clientSocket.Connect(ipep);
var command = "" + (char)27 + (char)97 + (char)14; //Epson command to get printer status
byte[] commandBytes = Encoding.ASCII.GetBytes(command);
clientSocket.Send(commandBytes );
var statusCode = clientSocket.Receive(commandBytes );
clientSocket.Close();
If the Printer is ready, statusCode got 3. Not getting any other codes.
Related
Zebra browser print is nice feature. I have able to print label from any browser app like Chrome, Firefox or even from the Postman api by sending API requests. Printer is connected through USB.
My problem is that I can not able to print the same from any windows app (Wpf/Winform). I have tried the TCP IP print with this code
NetworkStream ns = null;
Socket socket = null;
try
{
string ipAddress = "127.0.0.1";
int port = 9100;
var printerIP = new IPEndPoint(IPAddress.Parse(ipAddress), port);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(printerIP);
ns = new NetworkStream(socket);
byte[] toSend = Encoding.ASCII.GetBytes(zpl);
ns.Write(toSend, 0, toSend.Length);
}
finally
{
if (ns != null)
ns.Close();
if (socket != null && socket.Connected)
socket.Close();
}
But it is not working.
Also tried to send data from API
var data =
"{\"device\":{\"deviceType\":\"printer\",\"uid\":\"Zebra test printer\",\"provider\":\"com.zebra.ds.webdriver.desktop.provider.DefaultDeviceProvider\",\"name\":\"Zebra test printer\",\"connection\":\"driver\",\"version\":3,\"manufacturer\":\"Zebra Technologies\"}}, \r\n\"data\":\"^XA ^FT230,45,1 ^A0N,28,28 ^FD $1.00^FS ^XZ\"";
var client = new HttpClient();
var response = client.PostAsync(new Uri("http://127.0.0.1:9100/write"), new StringContent(data)).ConfigureAwait(false).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
MessageBox.Show("success");
}
var responseContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
MessageBox.Show(responseContent);
However this API code is working perfectly from any browser based app or from Postman
Here is my Browser print setting
Please let me know how can I print from the windows app?
I'm playing around with broadcasting and receiving UDP messages.
I have a client and a server that work ok in my machine, but that can't connect across machines.
My server sends messages and my client receives them.
I turned of the firewall on both machines, that can't be the problem.
The server looks like:
var udpclient = new UdpClient();
IPAddress multicastAddress = IPAddress.Parse("239.0.0.222");
udpclient.JoinMulticastGroup(multicastAddress);
var endPoint = new IPEndPoint(multicastAddress, 2222);
while(true)
{
Byte[] buffer = Encoding.Unicode.GetBytes(Dns.GetHostName());
udpclient.Send(buffer, buffer.Length, endPoint);
Console.WriteLine("Broadcasting server hostname: {0}", Dns.GetHostName());
Thread.Sleep(3000);
}
And the client looks like:
var client = new UdpClient { ExclusiveAddressUse = false };
var ipEndPoint = new IPEndPoint(IPAddress.Any, 2222);
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
client.ExclusiveAddressUse = false;
client.Client.Bind(ipEndPoint);
IPAddress multicastaddress = IPAddress.Parse("239.0.0.222");
client.JoinMulticastGroup(multicastaddress);
Byte[] data = client.Receive(ref ipEndPoint);
string strData = Encoding.Unicode.GetString(data);
Console.WriteLine("Received hostname {0} from the server", strData);
Console.WriteLine("I'm done. Press any key to close me.");
Console.ReadLine();
I think the problem is not in the code, but network related.
Any ideas on how to check what's the problem? Thank you in advance
Try connecting them to a same network such as a wifi network.Note: every time you connect to a different network the IP address changes.
I have this program and it is sending a string to a different socket on the same computer every 45 seconds. Below is the function which send a string over a socket using the built in Socket class of C#.
Issue I am having is that when I run this program and give 127.0.0.1 I am not getting any responses back from the socket. But when I run the program on a different computer using the ipaddress of the computer then it works flawlessly.
So I questioned if allowed to pass in 127.0.0.1 as the ip for the Socket class and have it recognize that I want to send data to a different socket on the same computer. Do I have to do anything different to make sure that it works on 127.0.0.1?
Thanks!
static string QueryMiner(string command)
{
byte[] bytes = new byte[1024];
try
{
//code for gettting current machines IP Use this code if client is running on the miner
IPAddress ipAddr = IPAddress.Parse("127.0.0.1");
//IPAddress ipAddr = IPAddress.Parse("198.xxx.xxx.xxx");
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4028);
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(ipEndPoint);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
string SummaryMessage = command;
byte[] msg = Encoding.ASCII.GetBytes(SummaryMessage);
sender.Send(msg);
byte[] buffer = new byte[1024];
int lengthOfReturnedBuffer = sender.Receive(buffer);
char[] chars = new char[lengthOfReturnedBuffer];
Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, lengthOfReturnedBuffer, chars, 0);
String SummaryJson = new String(chars);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
return SummaryJson;
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.ToString());
return ex.ToString();
}
}
The code where you set up the server portion of this (e.g. call bind) isn't here, but your problem is almost certianly that you are binding to a specific ip address and not to IPAddress.Any.
If so using your local IP rather than the loopback should work.
I am new to socket programming in C#. Have searched the web like crazy for the solution to my problem but didnt find anything that could fix it. So heres my problem:
I am trying to write a client-server application. For the time being, the server will also run on my local machine. The application transmits a byte stream of data from the client to the server. The problem is that the server doesnt detect a client request for connection, while the client is able to connect and transmit the byte stream.
here is the server code:
String strHostName = Dns.GetHostName();
Console.WriteLine(strHostName);
IPAddress ip = IPAddress.Parse("127.0.0.1");
ipEnd = new IPEndPoint(ip, port);
soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
soc.Bind(ipEnd);
Console.WriteLine("Web Server Running... Press ^C to Stop...");
Thread th = new Thread(new ThreadStart(StartListen));
th.Start();
The StartListen thread is as below:
public void StartListen()
{
try
{
while (true)
{
string message;
Byte[] bSend = new Byte[1024];
soc.Listen(100);
if (soc.Connected)
{
Console.WriteLine("\nClient Connected!!\n==================\n CLient IP {0}\n", soc.RemoteEndPoint);
Byte[] bReceive = new Byte[1024 * 5000];
int i = soc.Receive(bReceive);
The client code is as follows:
hostIPAddress = IPAddress.Parse("127.0.0.1");
ipEnd = new IPEndPoint(hostIPAddress,port);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Console.WriteLine("Connecting to Server...");
clientSocket.Connect(ipEnd);
Console.WriteLine("Sending File...");
clientSocket.Send(clientData);
Console.WriteLine("Disconnecting...");
clientSocket.Close();
Console.WriteLine("File Transferred...");
Now what happens is that the server starts and when I run the client, it connects, sends and closes. But nothing happens on the server console, it doesnt detect any connection: if (soc.Connected) remains false.
I checked whether the server was listening to 127.0.0.1:5050 through netstat, and it sure was listening. Cant figure out the problem. Please help.
On the server side use Socket.Accept Method to accept incoming connection. The method returns a Socket for a newly created connection: the Send() and Receive() methods can be used for this socket.
For example, after accepting the separate thread can be created to process the client connection (i.e. client session).
private void ClientSession(Socket clientSocket)
{
// Handle client session:
// Send/Receive the data.
}
public void Listen()
{
Socket serverSocket = ...;
while (true)
{
Console.WriteLine("Waiting for a connection...");
var clientSocket = serverSocket.Accept();
Console.WriteLine("Client has been accepted!");
var thread = new Thread(() => ClientSession(clientSocket))
{
IsBackground = true
};
thread.Start();
}
}
The following code sends a packet on port 15000:
int port = 15000;
UdpClient udp = new UdpClient();
//udp.EnableBroadcast = true; //This was suggested in a now deleted answer
IPEndPoint groupEP = new IPEndPoint(IPAddress.Broadcast, port);
string str4 = "I want to receive this!";
byte[] sendBytes4 = Encoding.ASCII.GetBytes(str4);
udp.Send(sendBytes4, sendBytes4.Length, groupEP);
udp.Close();
However, it's kind of useless if I can't then receive it on another computer. All I need is to send a command to another computer on the LAN, and for it to receive it and do something.
Without using a Pcap library, is there any way I can accomplish this? The computer my program is communicating with is Windows XP 32-bit, and the sending computer is Windows 7 64-bit, if it makes a difference. I've looked into various net send commands, but I can't figure them out.
I also have access to the computer (the XP one)'s local IP, by being able to physically type 'ipconfig' on it.
EDIT: Here's the Receive function I'm using, copied from somewhere:
public void ReceiveBroadcast(int port)
{
Debug.WriteLine("Trying to receive...");
UdpClient client = null;
try
{
client = new UdpClient(port);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
IPEndPoint server = new IPEndPoint(IPAddress.Broadcast, port);
byte[] packet = client.Receive(ref server);
Debug.WriteLine(Encoding.ASCII.GetString(packet));
}
I'm calling ReceiveBroadcast(15000) but there's no output at all.
Here is the simple version of Server and Client to send/receive UDP packets
Server
IPEndPoint ServerEndPoint= new IPEndPoint(IPAddress.Any,9050);
Socket WinSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
WinSocket.Bind(ServerEndPoint);
Console.Write("Waiting for client");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0)
EndPoint Remote = (EndPoint)(sender);
int recv = WinSocket.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message received from {0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
Client
IPEndPoint RemoteEndPoint= new IPEndPoint(
IPAddress.Parse("ServerHostName"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello, are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, RemoteEndPoint);