This pertains to my earlier post "http://stackoverflow.com/questions/8788825/linux-udp-server-unreachable-from-window-7", which has been solved. Now I am moving to my original job of connecting AVD to Linux server.
I am using the following code for connecting to the server
import java.net.*;
class UDPClient {
public final static int DesitnationPort = 9999;
private int mCounter;
private DatagramSocket mClientSocket;
private InetAddress mServerIPAddress;
private byte[] mDataBuffer;
private DatagramPacket mSendPacket;
private DatagramPacket mReceivePacket;
//Constructor
public UDPClient() {
//Time to make the private data good one
mCounter =1;
try {
mServerIPAddress = InetAddress.getByName("192.168.2.2");
}
catch(UnknownHostException e)
{
System.out.println("Host cannot be resolved :( ");
}
System.out.println("Host has been resolved The IP is valid one ");
try {
mClientSocket = new DatagramSocket();
}
catch(SocketException e)
{
System.out.println("Socket could not be created :( ==> " + e.getMessage());
}
System.out.println("Socket has been created ");
String temp = "This is from the Client == To my Dear Sever :) counter = " + mCounter;
mDataBuffer = temp.getBytes();
mSendPacket = new DatagramPacket(mDataBuffer, mDataBuffer.length, mServerIPAddress, DesitnationPort);
System.out.println("Datagram has been made now ");
System.out.println("Data ==>"+ mSendPacket.getData());
System.out.println("Data ==>"+ mSendPacket.getPort());
System.out.println("Data ==>"+ mSendPacket.getSocketAddress());
System.out.println("Data ==>"+ mSendPacket.getLength());
}
public void SendDataToServer(){
try {
if(!mClientSocket.isClosed()) {
String temp = "This is from the Client == To my Dear Sever :) counter = " + mCounter;
mDataBuffer = temp.getBytes();
mSendPacket = new DatagramPacket(mDataBuffer, mDataBuffer.length, mServerIPAddress, DesitnationPort);
mClientSocket.send(mSendPacket);
System.out.println("Send the packet");
mCounter++;
}
else {
System.out.println("Socket is closed");
}
}
catch(Exception e)
{
System.out.println("Could not send the data :( ==> " + e.getMessage());
}
}
public void ReceiveDataFromServer() {
byte[] tembuff = new byte[1024];
mReceivePacket = new DatagramPacket(tembuff, tembuff.length);
try {
if(!mClientSocket.isClosed()) {
mClientSocket.receive(mReceivePacket);
}
else {
System.out.println("Socket is closed");
}
}
catch(Exception e)
{
System.out.println("Could not Receive the data :( ");
return;
}
String data = new String(mReceivePacket.getData());
System.out.println(" Received the Data => " + data);
}
}
This code works well when I simply use the class in java program like this :-
class TryingWithClient {
public static void main(String a[]) {
UDPClient mClient = new UDPClient();
while(true) {
System.out.println("While Starting");
mClient.SendDataToServer();
mClient.ReceiveDataFromServer();
}
}
}
When I use the same code in AVD project I get a Null pointer exception at the following line :-
public void SendDataToServer(){
try {
if(!mClientSocket.isClosed()){ //<==# this call Null exception occurs
After browsing internet & android development sites I came to conclusion that I am missing the GMS / GPS functionality which I added to my AVD. Still I am unable to get any clue about this.
Here is my code which calls the above UDPClient.
public class StreamingProjectActivity extends Activity {
/** Called when the activity is first created. */
//All buttons
//private static final String LOG_TAG = "StreamingTest";
private StreamButton mStreamButton = null;
private UDPClient mClient= null;
class StreamButton extends Button {
boolean mStartStreaming = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onStream(mStartStreaming);
if (mStartStreaming) {
setText("Stop Streaming");
} else {
setText("Start recording");
}
mStartStreaming = !mStartStreaming;
}
};
public StreamButton(Context ctx) {
super(ctx);
setText("Start Streaming");
setOnClickListener(clicker);
}
}//class StreamButton Ends
#Override
public void onCreate(Bundle icicle) {
try {
mClient = new UDPClient();
System.out.println("==========> Client created sucessfully :) <====== ");
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mStreamButton = new StreamButton(this);
ll.addView(mStreamButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
System.out.println("Trying Step 2 now ");
}
catch(Exception e)
{
System.out.println("Activity could not be launched :( ");
}
}
//public StreamingTest()
public StreamingProjectActivity(){
System.out.println("Constructor ====>");
System.out.println("Constructor <====");
}//Constructor
private void onStream(boolean start) {
if (start)
{
mClient.SendDataToServer();
mClient.ReceiveDataFromServer();
try
{
Thread.sleep(4000);
}catch (InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}//onStream
}
Kindly help.
Ok, first of all: never ever print a catched exception with System.out.println("some msg " + e.getMessage()); Please use Log.e(TAG, "my message", e); for that. So you will actually see a stack trace.
Second: I bet that this code throws an error (check if you see the print in your LogCat output):
try {
mClientSocket = new DatagramSocket();
} catch(SocketException e) {
System.out.println("Socket could not be created :( ==> " + e.getMessage());
}
That is the only reason that mClientSocket still might be null. As this call might go wrong, you should consider checking for null before you check if the socket is closed.
The problem in my earlier solution was that I was mixing the GUI & network operations in the same thread which is called "StricMode.ThreadPolicy" (although, my problem is only part of what is mentioned in the jargon).
I was getting these exceptions "android.os.NetworkOnMainThreadException & android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) " which I could make out only after I applied WarrenFaith's suggestion (Thanks Warren).
These are thrown only on violation of "StricMode".
Solution : Simply separate the UI work from the network. I had to write the following code for this :
enum ClientThreadStates {
eUndefined,
eStopped,
eRunning,
eIdle,
eSendToServer,
eReadFromServer
}
public class ClientThread extends Thread {
private UDPClient mClient= null;
private ClientThreadStates mStateOfTheThread = ClientThreadStates.eUndefined;
private static String mLOG_TAG;
public ClientThread(String s){
mLOG_TAG = s;
mStateOfTheThread = ClientThreadStates.eStopped;
mClient = new UDPClient(s);
start();
}//constructor
public void SetState(ClientThreadStates paramState) {
mStateOfTheThread = paramState;
}
public ClientThreadStates GetState() {
return mStateOfTheThread;
}
private void Action(ClientThreadStates s) {
synchronized(s) {
switch(mStateOfTheThread) {
case eRunning: //fall
case eIdle: break;
case eSendToServer: mClient.SendDataToServer(); break;
case eReadFromServer: mClient.ReceiveDataFromServer(); break;
}
try {
mStateOfTheThread.wait();
}
catch( InterruptedException e ){
Log.e(mLOG_TAG, "Got Exception at wait <==", e);
}
}
}
public void run() {
mStateOfTheThread = ClientThreadStates.eRunning;
System.out.println("In Thread.run .. The State is " + mStateOfTheThread);
while(ClientThreadStates.eStopped.compareTo(mStateOfTheThread) < 0){ //state >stopped
Action(mStateOfTheThread);
}//while
}//run
}//class ClientThread
Finally synchronize on the two threads on the state like this :
private void onStream(boolean start) {
ClientThreadStates State = mClientThread.GetState();
synchronized(State) {
if (start) {
mClientThread.SetState(ClientThreadStates.eSendToServer);
}
else {
mClientThread.SetState(ClientThreadStates.eReadFromServer);
}
try {
State.notify();
}
catch( IllegalMonitorStateException e ) {
Log.e(LOG_TAG, "Got Exception # notify <==", e);
}
}
}//onStream
}//StreamingProjectActivity
Now the code runs perfectly.
Thanks.
Ashutosh
Related
I'm trying to create an object in one class then use that object in another class but each time I try to use it it just says the value is null
Customer cus = new Customer();
ServerSocket s = null;
public AddCustomer() {
}
public void getCustomerDetail() {
String back = " ";
{
try {
s = new ServerSocket(5433);
} catch (IOException e) {
System.out.println("Error:" + e.getMessage());
System.exit(0);
}
while (back.equals(" ")) {
try {
Socket s1 = s.accept();
System.out.println("Connection established at port 5433");
InputStream is = s1.getInputStream();
ObjectInputStream dis = new ObjectInputStream(is);
System.out.println("Getting data...");
cus = (Customer)dis.readObject();
System.out.println(cus.toString());
System.out.println(cus.getName());
dis.close();
s1.close();
System.out.println("Connection closed.");
} catch (ConnectException connExcep) {
System.out.println("1Error: " + connExcep.getMessage());
} catch (IOException ioExcep) {
System.out.println("2Error: " + ioExcep.getMessage());
} catch (Exception e) {
System.out.println("3Error: " + e.getMessage());
}
new AddCustomer().addCustomerToDB();
}
}
}
public void addCustomerToDB() {
System.out.println("start ");
Connection connection = null;
Statement statement = null;
int check = 1;
System.out.println(cus.getName()+"dadawd");
}
When I print out the value of cus.getName() it just gives me null but when I print it out in getCustomerDetail it gives me the correct value.
dis.readObject returns an object with the values in it.
Depends on what you are doing in the getName function and in the constructor.
Maybe in getCustomerDetails() you are setting the values in the input stream. But the default constructor doesn't do anything with name variable.
It looks like the issue of packaging. Try below code.
public class AddCustomer {
public static void main(String[] args) {
new AddCustomer().getCustomerDetail();
}
Customer cus = new Customer();
public void getCustomerDetail() {
String back = " ";
{
while (back.equals(" ")) {
try {
System.out.println(cus.toString());
System.out.println(cus.getName());
System.out.println("Connection closed.");
} catch (Exception e) {
System.out.println("3Error: " + e.getMessage());
}
new AddCustomer().addCustomerToDB();
break;
}
}
}
public void addCustomerToDB() {
System.out.println(cus.getName()+"dadawd");
}
}
class Customer{
private String name="ABC";
String getName() {
return name;
}
}
We found here one issue you have to create "Customer cus = new Customer();" this object under main() function like as
public class AddCustomer {
public static void main(String[] args) {
Customer cus = new Customer();
new AddCustomer().getCustomerDetail();
}
i'm trying to use Java Serial Communication to read measured values from a serial device. The task is to send the ASCII Code for 9 (57 in decimal) to the device and it will return the current value that is measured. In first place, I want to make sure that some value is correctly send back. So far, the connection works and when i changed the getListeningEvents() method to check for SerialPort.LISTENING_EVENT_DATA_WRITTEN it worked and showed me my phrase "Reading possible", but in this case this only shows that data got transferred.
So the number is send correctly, but I can't get an answer and the program gets stuck after printing "Written".
In many examples i saw the method notifyOnDataAvailable() for the SerialPort class, but i can't find it in the documentation anymore and i'm not sure if i have to use any other methods to initialize the listener. So my question is, what is wrong about my program, especially my EventListener, that it can't receive or identify the returned value?
Here is my code:
public class ConnectionNew implements SerialPortDataListener {
private SerialPort serialPort = null;
private java.io.OutputStream output = null;
private InputStream input = null;
private SerialPort [] ports = null;
public static void main(String[] args) {
ConnectionNew connect = new ConnectionNew();
connect.connectPort();
connect.initIOStream();
connect.initListener();
connect.writeData();
}
public void connectPort() {
ports = SerialPort.getCommPorts();
System.out.println("Select a port: ");
int i = 1;
for (SerialPort port : ports) {
System.out.println(i++ + ": " + port.getSystemPortName());
}
Scanner s = new Scanner(System.in);
int chosenPort = s.nextInt();
serialPort = ports[chosenPort - 1];
if (serialPort.openPort()) {
System.out.println("Port opened successfully");
} else {
System.out.println("Unable to open the port");
return;
}
}
public boolean initIOStream(){
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
System.out.println("Streams Connected");
return true;
}
public void initListener() {
serialPort.addDataListener(this);
}
public void writeData(){
try {
output.write(57);
output.flush();
System.out.println("Written");
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public int getListeningEvents() {
return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
}
#Override
public void serialEvent(SerialPortEvent arg0) {
System.out.println("Reading possible");
}
}
I'm very happy about any hints, thanks in advance!!
You need to get the data from the event:
public void serialEvent(SerialPortEvent e) {
byte[] data = e.getReceivedData​();
// ...
}
I am trying to make a plugin that has a 'global' configuration file. Right now, I'm trying to use Plugin Messaging to send the entire configuration file through a string, to another server. I have followed the guide at https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/ and have put my own little twist on what is sent. I'm trying to send the plugin message within a spigot plugin so maybe that is the problem. Here is the code is a summary of the code I use to send it (I took out readFile(), clearFile() and writeFile(), let me know if you want those):
public class Main extends JavaPlugin implements PluginMessageListener {
public void onEnable() {
this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
this.getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", this);
}
public void onDisable() {}
public void updateConfig() {
String updateConfig = "";
for (String s : readFile(this.getDataFolder() + "/config.yml")) {
if (updateConfig.equals("")) {
updateConfig = s;
} else {
updateConfig = updateConfig + " |n| " + s;
}
}
Bukkit.getLogger().info("Sending config update...");
sendUpdateconfig(updateConfig);
}
public void sendUpdateconfig(String update) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
try {
out.writeUTF("Forward");
out.writeUTF("ALL");
out.writeUTF("FooServer");
ByteArrayOutputStream msgbytes = new ByteArrayOutputStream();
DataOutputStream msgout = new DataOutputStream(msgbytes);
msgout.writeUTF(update);
msgout.writeShort(295);
out.writeShort(msgbytes.toByteArray().length);
out.write(msgbytes.toByteArray());
Player player = Iterables.getLast(Bukkit.getOnlinePlayers());
player.getServer().sendPluginMessage(this, "BungeeCord", out.toByteArray());
Bukkit.getLogger().info("Sent " + update);
Bukkit.getLogger().info("Short sent: 295");
Bukkit.getLogger().info("Sent through player " + player.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onPluginMessageReceived(String channel, Player player, byte[] message) {
Bukkit.getLogger().info("Recieved message...");
if (!channel.equals("BungeeCord")) {
return;
}
try {
Bukkit.getLogger().info("Recieved message...");
ByteArrayDataInput in = ByteStreams.newDataInput(message);
String subChannel = in.readUTF();
if (!subChannel.equals("FooServer")) {
Bukkit.getLogger().info("Loading message....");
short len = in.readShort();
byte[] msgbytes = new byte[len];
in.readFully(msgbytes);
DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes));
String somedata = msgin.readUTF();
short somenumber = msgin.readShort();
if (somenumber == 295) {
Bukkit.getLogger().info("Updating config...");
String[] toWrite = somedata.split(" |n| ");
String path = (this.getDataFolder() + "/config.yml");
clearFile(path);
for (String s : toWrite) {
writeFile(path, s);
}
Bukkit.getLogger().info("Config updated!");
}
} else {
Bukkit.getLogger().info("Message sent by this plugin.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The way I send the message is just by calling, updateConfig(); When that is called, onPluginMessageReceived is never run.
Is there something I'm doing wrong? Can plugin messages only be sent by a bungeecord plugin? Thanks in advance. If you have any questions about the code, let me know.
Don't work beacause it's write ( String server to send to, or ALL to send to every server (except the one sending the plugin message)) ! For use it you can use our own channel or redis
My scheme: ajax long polling to Tomcat. Tomcat executes selenium "operations".
Im trying to execute selenium scenario from tomcat.
Its working ok but i need to get logs back to js client.
Javascript client partially receives messages from server when selenium working.
Inside some selenium operations im using Thread.sleep(). Maybe mistakes because of this ?
Please tell me why messages partially received (i think) by client
Here is ServerInfoLogger. BaseLogger outputs messages to console and file
public class ServerInfoLogger extends BaseLogger {
public ServerSession clientServerSession;
protected void logToClient(String message) {
super.log(message);
sendMessage(message);
}
// Server.serverSession and Server.clientServerSession not null but messages partially not received by client
private void sendMessage(String message) {
// send message to client
if (Server.serverSession!=null && Server.clientServerSession!=null) {
Server.clientServerSession.deliver(Server.serverSession, "/message", message);
} else {
System.err.println("Server error. Server.serverSession=" + Server.serverSession + " clientServerSession=" + clientServerSession);
}
}
}
Here is selenium scenario
public class Task extends ServerInfoLogger {
public static boolean datesAvailable = false;
private TaskParser parser = new TaskParser();
protected ArrayList<Step> steps = new ArrayList<>();
private WebDriver webDriver;
protected int currentStepIndex = 0;
protected Step currentStep;
private WebDriverFactory webDriverFactory = new WebDriverFactory();
private int currentTryout = 1;
private int maxTryouts = 40;
public Task(ServerSession clientServerSession, String taskData) {
this.clientServerSession = clientServerSession;
logToClient("new task"); // client always receives this message
steps = parser.parse(taskData);
logToClient("steps parsed. total: "+steps.size()); // client always receives this message
start();
}
protected void start() {
createWebDriver();
startStep();
}
protected void startStep() {
currentStep = steps.get(currentStepIndex);
currentStep.setWebDriver(webDriver);
currentStep.clientServerSession = clientServerSession;
boolean stepComplete = false;
try {
stepComplete = currentStep.start();
} catch (StepException e) {
logToClient(e.getMessage()+" step id: "+e.getStepId());
e.printStackTrace();
}
log("step complete = "+stepComplete);
if (stepComplete) {
onStepComplete();
} else {
onStepError();
}
}
private void onStepError() {
currentTryout++;
if (currentTryout > maxTryouts) {
destroyWebDriver();
logToClient("Max tryouts reached"); // client never receives this message
} else {
logToClient("Step not complete. Restarting task. currentTryout=" + currentTryout); // client partially receives this message
restart();
}
}
private void onStepComplete() {
currentStepIndex++;
if (currentStepIndex < steps.size()) {
startStep();
} else {
destroyWebDriver();
taskComplete();
}
}
private void destroyWebDriver() {
webDriver.quit();
webDriver = null;
}
private void taskComplete() {
logToClient("Task complete !!!"); // client **never** receives this message
TaskEvent taskEvent = new TaskEvent(TaskEvent.TASK_COMPLETE);
EventDispatcher.getInstance().dispatchEvent(taskEvent);
}
public void restart() {
logToClient("Task restart");
try {
setTimeout(Application.baseOperationWaitSecondsUntil);
new SwitchToDefaultContentOperation().execute();
} catch(OperationException exception) {
logToClient("Cannot get default content"); // client partially receives this message
}
currentStepIndex = 0;
startStep();
}
private void setTimeout(int seconds) {
webDriver.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS);
}
private void createWebDriver() {
webDriver = webDriverFactory.getDriver(BrowserType.CHROME).getDriver();
}
public int getCurrentStepIndex() {
return currentStepIndex;
}
}
Here is creation of logger
private void createLogger() {
Date currentDate = new Date();
String logFilePostfix = currentDate.getMonth()+"_"+currentDate.getDate()+"-"+currentDate.getHours()+"_"+currentDate.getMinutes()+"_"+currentDate.getSeconds();
logger = Logger.getLogger(appName);
logger.setUseParentHandlers(false);
FileHandler fh;
SimplestFormatter formatter = new SimplestFormatter();
try {
fh = new FileHandler("C:\\consultant\\logs\\log_"+logFilePostfix+".txt");
logger.addHandler(fh);
fh.setFormatter(formatter);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Selenium operation with Thread.sleep()
public class SwitchToMainFrameOperation extends BaseOperation {
private WebElement mainIframe;
private WebDriverWait wait;
#Override
public boolean execute() throws OperationException {
switchToRoot();
sleepThread();
log("switchToMainIFrame by xPath "+Page.getMainIframeXPath()); // log to console and file
wait = new WebDriverWait(webDriver, Application.baseOperationWaitSecondsUntil);
try {
mainIframe = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(Page.getMainIframeXPath())));
webDriver.switchTo().frame(mainIframe);
log("main frame switch OK"); // log to console and file
} catch(StaleElementReferenceException exception) {
log("main frame switch error. StaleElementReferenceException - trying again"); // log to console and file
wait = null;
sleepThread();
execute();
}
return true;
}
private void switchToRoot() {
log("switch to root");
webDriver.switchTo().defaultContent();
}
private void sleepThread() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
As part of my lab this week I am suppose to convert a socket based chat application to RMI. So far I managed to connect server and client together and transfer data between them but the transfer is not continuous. What I mean is that when the client first connects t the server it broadcasts a message "X has entered the conversation" but that is all. Anything I type after that wont get broadcasted. I am about to pull out my hair. Please help.
public class ChatServer extends UnicastRemoteObject implements ChatMessage {
private static final long serialVersionUID = 1L;
private String sender;
private String message;
private ChatMessageType t;
public ChatServer() throws RemoteException {
super();
}
#Override
public void Message(String sender, ChatMessageType t, String message)
throws RemoteException {
this.sender = sender;
this.message = message;
this.t = t;
}
#Override
public String getSender() throws RemoteException {
return sender;
}
#Override
public String getMessage() throws RemoteException {
return message;
}
#Override
public ChatMessageType getType() throws RemoteException {
return t;
}
public String ToString() throws RemoteException{
String strMessage;
switch (t) {
case SETUP:
strMessage = sender + " has entered the conversation.";
break;
case TEARDOWN:
strMessage = sender + " has left the conversation.";
break;
case MESSAGE:
strMessage = sender + ": " + message;
break;
default:
strMessage = "";
}
return strMessage;
}
// driver.
public static void main(String arg[]) {
try {
ChatServer c = new ChatServer();
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("Server", c);
System.out.println("Server bound in registry");
} catch (Exception e) {
System.out.println("Server error: " + e.getMessage());
e.printStackTrace();
}
}
}
public class ChatClient implements ActionListener {
// static private Socket c;
static ChatMessage obj = null;
// static private ObjectInputStream in;
// static private ObjectOutputStream out;
static private String name;
static private String host;
static private Integer port;
/**
* Launches this application
*/
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (args.length != 3) {
System.out
.println("Client requires exactly three args to run.");
System.exit(-1);
}
name = args[0];
host = args[1];
port = new Integer(args[2]);
final ChatClient application = new ChatClient();
application.getJFrame().setVisible(true);
try {
System.out.println("client: connecting to server...");
// c = new Socket(host, port);
obj = (ChatMessage) Naming.lookup("//" + host + ":" + port
+ "/Server");
System.out.println("client: connected!");
} catch (Exception e) {
System.out.println("client: " + e.getMessage());
System.exit(-1);
}
try {
// out = new ObjectOutputStream(c.getOutputStream());
// in = new ObjectInputStream(c.getInputStream());
// announce to other clients that you're here
// out.writeObject(new ChatMessage(name,
// ChatMessageType.SETUP, ""));
obj.Message(name, ChatMessageType.SETUP, "");
} catch (Exception e) {
}
// set up the client's listener as an anonymous thread that's
// always running
// new Thread(new Runnable(){
// public void run()
// {
// while(true)
// {
try {
System.out.println(name + ": waiting for data");
ChatMessage m = (ChatMessage) Naming.lookup("//" + host
+ ":" + port + "/Server");
System.out.println(name + ": data received");
application.updateTextArea(m.ToString());
} catch (Exception e) {
}
// }
// }
// }).start();
}
});
}
public void updateTextArea(final String message) {
conversation.setText(conversation.getText() + message + "\n");
// this will guarantee that the bottom of the conversation is visible.
conversation.setCaretPosition(conversation.getText().length());
}
// send button has been pressed, send the message to the server.
public void actionPerformed(ActionEvent e) {
if (send.getText().equals("Send")) {
try {
System.out.println(name + ": sending data");
// ChatMessage m = new ChatMessage(name,
// ChatMessageType.MESSAGE, message.getText());
// out.writeObject(m);
obj.Message(name, ChatMessageType.MESSAGE, message.getText());
message.setText(""); // clear the text box.
System.out.println(name + ": data sent");
} catch (Exception ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
}
}
enum ChatMessageType{
SETUP,
MESSAGE,
TEARDOWN
}public interface ChatMessage extends Remote{
public String getSender() throws RemoteException;
public String getMessage() throws RemoteException;
public ChatMessageType getType() throws RemoteException;
public void Message(String sender, ChatMessageType t, String message) throws RemoteException;
public String ToString() throws RemoteException;
I realize this question is pretty old and you probably figured out an answer for this, but, I thought I'd share an approach I took for going from Java sockets to RMI. Maybe it is useful for others looking to do the same thing.
I basically abstracted out the socket portion into a "Tunnel" object that represents a communication path between hosts. And the tunnel consists of several "channels", that represent a one-way communication between the source and destination.
You can check out more details at my blog here: http://www.thecodespot.com/?p=1