Search code examples
javapythonclient-servertwisted

Twisted python server and Java chat


i have found this amazing tutorial on raywenderlich.com:

http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server

it create a Twisted Python server, and talk with app iphone chat, i would let the server talk also with a Java chat, and now i write some code, this is the python server:

from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor


class IphoneChat(Protocol):
def connectionMade(self):
    #self.transport.write("""connected""")
    self.factory.clients.append(self)
    print "clients are ", self.factory.clients

def connectionLost(self, reason):
    self.factory.clients.remove(self)

def dataReceived(self, data):
    #print "data is ", data
    a = data.split(':')
    if len(a) > 1:
        command = a[0]
        content = a[1]

        msg = ""
        if command == "iam":
            self.name = content
            msg = self.name + " has joined"

        elif command == "msg":
            msg = self.name + ": " + content

        print msg

        for c in self.factory.clients:
            c.message(msg)

def message(self, message):
    self.transport.write(message + '\n')


factory = Factory()
factory.protocol = IphoneChat
factory.clients = []

reactor.listenTCP(1025, factory)
print "Chat server started"
reactor.run()

then i create a simple java example to connect to the server:

import java.net.*;
import java.io.*;
import java.util.*;

public class MyClassSocket  {

private ObjectInputStream sInput;       // to read from the socket
private ObjectOutputStream sOutput;     // to write on the socket
private Socket socket;

private String server, username;
private int port;

MyClassSocket(String server, int port, String username) {
    this.server = server;
    this.port = port;
    this.username = username;
}

private void display(String msg) {

    System.out.println(msg);      // println in console mode

}

public boolean start() {

    try {
        socket = new Socket(server, port);
    }
    // if it failed not much I can so
    catch(Exception ec) {
        display("Error connectiong to server:" + ec);
        return false;
    }

    String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
    display(msg);

    try
    {

        sInput  = new ObjectInputStream(socket.getInputStream()); //<-------- block here
        sOutput = new ObjectOutputStream(socket.getOutputStream());
    }
    catch (IOException eIO) {
        display("Exception creating new Input/output Streams: " + eIO);
        return false;
    }

    return true;

}

public static void main(String[] args) {

    MyClassSocket client = new MyClassSocket("localhost",1025,"PieroJava");
    client.start();
}

}

The code freeze in the point i comment in the code above, and i can see in the server terminal that there is a new connection, and i can see in the client terminal that i connect but don't go over here:

sInput  = new ObjectInputStream(socket.getInputStream());

how i can do?


Solution

  • I suggest not using ObjectInputStream and ObjectOutputStream. It will probably be challenging to get these to interact nicely with a Python server anyway, and they don't implement a very good protocol anyway. I recommend a simpler protocol with better cross language support such as AMP.

    In any case, new ObjectInputStream seems to be expected to block until it can read bytes from the connection. If you want to make it succeed, your Twisted-based server will need to write the beginning of a Java object stream to the connection.