I am trying ti print a string to an RFID Printer using sockets. Here is my code. When i call :
Print p = new Print();
p.printToIP();
I get this error: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
Here is my class code:
class Print
{
public string printerIP { get; set; }
public int printerPort { get; set; }
public string myZPL { get; set; }
private EndPoint ep { get; set; }
private Socket sock { get; set; }
private NetworkStream ns { get; set; }
//private AsyncCallback callbackWrite;
public Print()
{
printerIP = "127.0.0.1";
printerPort = 9001;
myZPL = "AN12345";
}
public void printToIP()
{
ep = new IPEndPoint(IPAddress.Parse(printerIP), printerPort);
sock = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(ep);
sock.Listen(10);
try
{
sock.Connect(ep);
ns = new NetworkStream(sock);
byte[] toSend = Encoding.ASCII.GetBytes(myZPL);
ns.BeginWrite(toSend, 0, toSend.Length, OnWriteComplete, null);
ns.Flush();
}
catch (Exception ex)
{
sock.Shutdown(SocketShutdown.Both);
sock.Close();
}
}
private void OnWriteComplete(IAsyncResult ar)
{
NetworkStream thisNS = ns;
thisNS.EndWrite(ar);
sock.Shutdown(SocketShutdown.Both);
sock.Close();
}
You get this error because you sent data before your client connected .
....
var res = sock .BeginAccept(AcceptCallback, null);
}
private void AcceptCallback(IAsyncResult result)
{
Socket socket = sock .EndAccept(result);
while (true)
{
sock.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None,
new AsyncCallback(ReceiveCallBack), socket);
_resetEvent.WaitOne();
_resetEvent.Reset();
}
}
....
You should not use a listner socket to Transfer data, you should use a client socket for send or receive data, Usully listener sockets are used only a receiption. Use a client socket then your problem will be solved.
Here you are creating a Listner socket not a client socket
sock = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(ep);
sock.Listen(10);
The proper way would be to create a new instance of socket and connect it to Endpoints
And IF I were you i wouldn't use Socket class, instead I would use TCPClinet/ TCPListner classes provided by framwork.
For Tcpclinet class that would be like this
System.Net.Sockets.TcpClient clinet = new System.Net.Sockets.TcpClient();
clinet.Connect(endpoint_object);
For normal Socket class that would be this , So you must use the below code in your case
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
clientSock.Connect(ipEnd);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.