barcode printer 使用 php socket 列印
話說,條碼印表機實在很神秘,要讓它印個條碼非得透過特定應用程式不可,這次很幸運可以試著自已把東東印出來,透過之前從沒用過的 socket ,socket 這東東看了半天也看不懂是個什麼東西 ,不過本著一貫在不解中摸黑,只問結果不求甚解的鴕鳥心態,就……試試。
$cht_string = "我要用中文";
$cht_string = iconv(mb_detect_encoding($cht_string), "UTF-8", $cht_string);
$cht_big5 = iconv(mb_detect_encoding($cht_string), "BIG-5", $cht_string);
$host = "1.2.3.4";
$port = 9100; //default listening port for printer
$message = '
Hello, world'.$cht_string.$cht_big5.'
';
// create socket
// 0, IP
// SOL_TCP = specify protocol of TCP, UDP, FTP ...
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if(!$socket){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
socket_close($socket);
die("Could not create socket: [$errorcode] $errormsg\n");
}
// connect to server
$result = socket_connect($socket, $host, $port);
if(!$result){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
socket_close($socket);
die("Could not connect to server: [$errorcode] $errormsg\n");
}
// send string to server
$socket_wrt = socket_write($socket, $message, strlen($message));
if(!$socket_wrt){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
socket_close($socket);
die("Could not send data to server: [$errorcode] $errormsg\n");
}
echo "Reply From Server:".$result;
// close socket
socket_close($socket);
$cht_string = "我要用中文";
$cht_string = iconv(mb_detect_encoding($cht_string), "UTF-8", $cht_string);
$cht_big5 = iconv(mb_detect_encoding($cht_string), "BIG-5", $cht_string);
$host = "1.2.3.4";
$port = 9100; //default listening port for printer
$message = '
Hello, world'.$cht_string.$cht_big5.'
';
// create socket
// 0, IP
// SOL_TCP = specify protocol of TCP, UDP, FTP ...
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if(!$socket){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
socket_close($socket);
die("Could not create socket: [$errorcode] $errormsg\n");
}
// connect to server
$result = socket_connect($socket, $host, $port);
if(!$result){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
socket_close($socket);
die("Could not connect to server: [$errorcode] $errormsg\n");
}
// send string to server
$socket_wrt = socket_write($socket, $message, strlen($message));
if(!$socket_wrt){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
socket_close($socket);
die("Could not send data to server: [$errorcode] $errormsg\n");
}
echo "Reply From Server:".$result;
// close socket
socket_close($socket);
只要設備支援 socket 以上的源碼就可以連線、列印,message 的部份當然是要符合印表機規定的格式,只是有時侯遇到印出了亂碼時要注意編碼的轉換。
收工!
留言
張貼留言