Hi,
Kindly help me debug the error message I am getting while using JSON
messenger (mentioned in the previous e-mail). While the simple messenger is
useful, JSON messenger would be much more convenient for me.
In the meanwhile, I was trying to write to the socket analogously in Nodejs
for a "simple" messenger:-
This is my working code in Node.js:-
var net = require('net');
var HOST = 'localhost';
var PORT = 2603;
var socket = net.createConnection(PORT, HOST);
socket.setEncoding("utf8");
socket.on('error', function(error) {
res.send(404, HOST, PORT);
});
socket.on('connect', function(connect) {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
var s="hello";
var buf = new Buffer(3);
var num = 3+s.length;
buf.writeInt16BE(num, 0);
buf.writeInt8(42, 2);
socket.write(buf);
socket.write(s);
socket.end();
socket.on('end', function() {
console.log('socket closing...');
});
socket.on('data', function(data) {
console.log(data);
});
});
Also, I had to go through quite some code files using the references from
previous threads to build a messenger client. I thought I'd post it for
users' reference :)
This is the code to a working python messenger client:
import socket, time, threading, sys, struct
host = '127.0.0.1'
port = 2603
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.settimeout(3.0)
try:
s.connect((host,port))
except socket.error:
print host ,'is offline, stop '
exit()
try:
data='hello'
s.send(struct.pack("!HB",(3+len(data)),42)+data)
#data = s.recv(1024)
#print host, 'says:', data
except socket.error:
print host,'is offline, stop '
exit()
s.close()
And the working java client I started testing the messenger with:-
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author jneha
*/
public class Jsock {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
// TODO code application logic here
Socket newsock = new Socket("localhost", 2603);
System.out.println("Connected to localhost in port 2603");
DataOutputStream dos = new
DataOutputStream(newsock.getOutputStream());
String s = "hello";
dos.writeShort(3 + s.length());
dos.writeByte(42); // Arbitrary 'type' value
dos.writeBytes(s);
dos.close();
newsock.close();
} catch (IOException ex) {
Logger.getLogger(Jsock.class.getName()).log(Level.SEVERE, null,
ex);
}
}
}
Regards,
Neha