Using JavaOsc to get meter readings from a Behringer X32 - java

I am trying to work with JavaOsc but I am having difficulties establishing a connection. My test code is below, but it does not matter what IP address port I put in, it appears to connect (which is not correct) and there is no response I am receiving. So I am doing something wrong, but find it hard to find documentation.
final static private int port = 10023;
final static private String ipAddess = "192.168.1.78";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
OSCPortOut sender = null;
OSCPortIn receiver = null;
try {
//receiver = new OSCPortIn(10023);
OSCMessageListener msgListener = new OSCMessageListener() {
#Override
public void acceptMessage(OSCMessageEvent oscMessageEvent) {
System.out.println("Message received A! " + oscMessageEvent.toString());
}
};
OSCPacketListener listener = new OSCPacketListener() {
#Override
public void handlePacket(OSCPacketEvent oscPacketEvent) {
System.out.println("Package received A! " + oscPacketEvent.toString());
}
#Override
public void handleBadData(OSCBadDataEvent oscBadDataEvent) {
System.out.println("Package BAD received B!");
}
public void acceptMessage(java.util.Date time, OSCMessage message) {
System.out.println("Message received!");
}
};
MessageSelector selector = new MessageSelector() {
#Override
public boolean isInfoRequired() {
System.out.println("Info required call");
return false;
}
#Override
public boolean matches(OSCMessageEvent oscMessageEvent) {
System.out.println("Message match?? " + oscMessageEvent.toString());
return false;
}
};
receiver = new OSCPortInBuilder().addPacketListener(listener).addMessageListener(selector, msgListener).setLocalPort(port).setRemotePort(port).build();
receiver.connect();
receiver.startListening();
sender = new OSCPortOut(InetAddress.getByName(ipAddess), port);
sender.connect();
System.out.println("Remote address: " + sender.getRemoteAddress() + " local: " + sender.getLocalAddress());
List<String> vars = new ArrayList<String>();
vars.add("/info");
OSCMessage msg = new OSCMessage("/msgAddress", vars);
System.out.println("Is connected: " + sender.isConnected());
sender.send(msg);
System.out.println("Msg info: " + msg.getInfo() + " - " + msg.getAddress());
System.out.println("Deamon: " + receiver.isDaemonListener() + " is listening " + receiver.isListening() + " is connected " + receiver.isConnected());
System.out.println("Please type 'q' to stop.");
if(scanner.nextLine().equalsIgnoreCase("q")) break;
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace(System.out);
} finally {
try {
if (sender != null) sender.close();
if (receiver != null) receiver.close();
} catch (IOException e){
System.out.println("Problem closing: " + e.getMessage());
}
}
}
System.out.println("Finished.");
The response is:
Info required
Remote address: /192.168.1.78:10023 local: /0.0.0.0:0
Is connected: true
Msg info: null - /msgAddress
Deamon: true is listening true is connected true
Please type 'q' to stop.
I also tried to contact the local receiver (using 127.0.0.1) but that didn't work either.
Any suggestions would be really appreciated!

Related

Java StreamCorrupted when connecting more than one Client to Server

Explanation
I'm currently trying to create a Multiplayer Game with Java where up to five Players can play together.
The problem is that when I'm trying to connect multiple Clients to my Server I get an Exception and the Server doesn't work anymore.
With one Client at a time, everything works fine.
So what I need is a Server that can handle up to five players at a time and the clients should always get some new game data from the Server
every few seconds (Connected Players, etc.).
The "Game data" in the code below is the String I'm sending through the Object Stream.
Normally I would send an Object which has all the game data, but with the String, I get the same problem.
I'm struggling with the problem that only one Client can connect without any errors occurring for some days now and I didn't find a solution to my problem.
I saw that there are things like java.nio or the ExecutorService, but I didn't really understand those that much, so I don't know if they can help.
I have made a smaller program that simulates the same problem I get with my bigger program.
To Start the Server, you need to Start the GameMultiPlayerCreate.java Class, and for the Client, the Client.java class.
I'm new to Sockets so if something is unnecessary or if something can be made better please let me know.
So the Error I'm getting when I connect two or more Clients is:
java.io.StreamCorruptedException: invalid stream header: 00050131
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Server.waitForData(Server.java:89) //I highlighted that in the code with a comment
at Server.loopWaitForData(Server.java:49)
at Server.run(Server.java:34)
at java.lang.Thread.run(Unknown Source)
Code
GameMultiPlayerCreate.java: Should start the Server threads if a Client connects
public class GameMultiPlayerCreate {
ServerSocket socketServer = null;
static String settingIp = "localhost";
static String settingPort = "22222";
static byte settingPlayers = 5;
public static int connectedPlayers = 0;
public static void main(String[] args) {
try {
GameMultiPlayerCreate objGameMultiPlayerCreate = new GameMultiPlayerCreate();
objGameMultiPlayerCreate.createServer();
} catch (NumberFormatException | IOException | InterruptedException e) {
e.printStackTrace();
}
}
public void createServer() throws NumberFormatException, UnknownHostException, IOException, InterruptedException {
while (connectedPlayers < settingPlayers) {
socketServer = new ServerSocket(Integer.parseInt(settingPort), 8, InetAddress.getByName(settingIp));
System.out.println("Server is waiting for connection...");
Socket socket = socketServer.accept();
new Thread(new Server(socket)).start();
Thread.sleep(5000);
socketServer.close();
}
}
}
Server.java: This is the Class of which a new Thread should be created for each connected Client (Client Handler)
public class Server implements Runnable {
protected static Socket socket = null;
private int loops;
private int maxLoops = 10;
private int timeout = 10000;
protected static boolean killThread = false;
private boolean authenticated = true; //true for testing
protected static String ip;
protected static int port;
public Server(Socket socket) throws IOException {
Server.socket = socket;
}
public void run() {
try {
socket.setSoTimeout(timeout);
} catch (SocketException e) {
System.out.println("Error while trying to set Socket timeout. ");
System.out.println("Closing Thread..." + Thread.currentThread());
disconnectClient();
}
if (!killThread) {
GameMultiPlayerCreate.connectedPlayers = GameMultiPlayerCreate.connectedPlayers + 1;
loopWaitForData();
}
}
private void disconnectClient() {
System.out.println("Kicking Client... " + Thread.currentThread());
killThread = true;
GameMultiPlayerCreate.connectedPlayers = GameMultiPlayerCreate.connectedPlayers - 1;
}
public void loopWaitForData() {
while (!killThread) {
System.out.println(maxLoops + ", " + loops);
if (maxLoops - loops > 0) {
try {
waitForData();
} catch (SocketTimeoutException e) {
System.out.println("Error occurred while waiting for Data. Thread disconnected? Sending reminder. " + Thread.currentThread());
if (!authenticated) {
System.out.println("Kicking Client: Not authenticated");
disconnectClient();
} else {
commandReminder();
}
} catch (ClassNotFoundException | IOException e) {
loops = loops + 1;
System.out.println("Error occurred while waiting for Data. Waiting for more Data. " + Thread.currentThread());
e.printStackTrace();
loopWaitForData();
}
} else if (maxLoops - loops == 0) {
System.out.println("Error occurred while waiting for Data. Maximum trys reached. Disbanding connection. " + Thread.currentThread());
disconnectClient();
loops = loops + 1;
} else {
System.out.println("Closing Thread..." + Thread.currentThread());
disconnectClient();
}
}
}
private void commandReminder() {
System.out.println("Reminder");
try {
String code = new String("0");
ObjectOutputStream outputObject = new ObjectOutputStream(Server.socket.getOutputStream());
outputObject.writeObject(code);
} catch (IOException e) {
System.out.println("Error occurred while trying to authenticate Client: " + e + " in " + Thread.currentThread());
}
}
public void waitForData() throws IOException, ClassNotFoundException {
String code;
System.out.println("Waiting for Data...");
//Next line is where the error occurres
ObjectInputStream inputObject = new ObjectInputStream(socket.getInputStream());
while ((code = (String) inputObject.readObject()) != null) {
System.out.println("Received Data...");
System.out.println("Input received: " + code);
return;
}
}
}
Client.java: This is the Client
public class Client {
public static Socket socket = new Socket();
private int loops = 0;
private int maxLoops = 10;
private static boolean killThread = false;
private String ip;
private int port;
public Client(String receivedIp, String receivedPort) {
ip = receivedIp;
port = Integer.parseInt(receivedPort);
try {
System.out.println("Trying to connect to Server...");
socket.connect(new InetSocketAddress(ip, port));
System.out.println("Connected!");
} catch (IOException e) {
System.out.println("Error occurred while trying to connect to Server.");
}
loopWaitForData();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Client objClient = new Client("localhost", "22222");
}
public void loopWaitForData() {
while (!killThread) {
System.out.println(maxLoops + ", " + loops);
if (maxLoops - loops > 0) {
try {
waitForData();
} catch (IOException | ClassNotFoundException e) {
loops = loops + 1;
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
}
System.out.println("Error occurred while waiting for Data. Waiting for more Data. " + Thread.currentThread());
e.printStackTrace();
loopWaitForData();
}
} else if (maxLoops - loops == 0){
System.out.println("Error occurred while waiting for Data. Maximum trys reached. Disbanding connection. " + Thread.currentThread());
try {
socket.close();
} catch (IOException e) {
System.out.println("Failed to close Socket " + Thread.currentThread());
}
loops = loops + 1;
} else {
System.out.println("Closing Thread..." + Thread.currentThread());
killThread = true;
}
}
}
public void waitForData() throws IOException, ClassNotFoundException {
InputStream input = socket.getInputStream();
ObjectInputStream inputObject = new ObjectInputStream(input);
String code;
System.out.println("Waiting for Data...");
while ((code = (String) inputObject.readObject()) != null) {
System.out.println("Received Data...");
System.out.println("Input received: " + code);
answer();
return;
}
}
private void answer() {
try {
String code = new String("1");
ObjectOutputStream outputObject = new ObjectOutputStream(socket.getOutputStream());
outputObject.writeObject(code);
} catch (IOException e) {
System.out.println("Error occurred while trying to answer: " + e + " in " + Thread.currentThread());
}
}
}

How does TCP connection works on Android?

I am using smack for building a chat app in Android. I am using a sticky_service to hold the connection. I have a confusion that if my app goes to sleep what happens to TCP connection. I have read few answers on the page - How to make the Android device hold a TCP connection to Internet without wake lock?
It wakes up for a brief period of time - For smack I can think of it as the processmessage listener (http://www.programcreek.com/java-api-examples/index.php?api=org.jivesoftware.smack.MessageListener) is called. I am inserting data in db for that. Is there any guarantee that work will be complete or if the execution is left in between will it be started from there.
Hello dear you can use this code snippet :
protected void connect() {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
features.encryptionEnabled = false;
lastConnect = SystemClock.elapsedRealtime();
lastPingSent = SystemClock.elapsedRealtime();
this.attempt++;
try {
shouldAuthenticate = shouldBind = !account.isOptionSet(Account.OPTION_REGISTER);
tagReader = new XmlReader(wakeLock);
tagWriter = new TagWriter();
packetCallbacks.clear();
this.changeStatus(Account.State.CONNECTING);
final Bundle result = DNSHelper.getSRVRecord(account.getServer());
final ArrayList<Parcelable> values = result.getParcelableArrayList("values");
if ("timeout".equals(result.getString("error"))) {
throw new IOException("timeout in dns");
} else if (values != null) {
int i = 0;
boolean socketError = true;
while (socketError && values.size() > i) {
final Bundle namePort = (Bundle) values.get(i);
try {
String srvRecordServer;
try {
srvRecordServer = IDN.toASCII(namePort.getString("name"));
} catch (final IllegalArgumentException e) {
// TODO: Handle me?`
srvRecordServer = "";
}
final int srvRecordPort = namePort.getInt("port");
final String srvIpServer = namePort.getString("ip");
final InetSocketAddress addr;
if (srvIpServer != null) {
addr = new InetSocketAddress(srvIpServer, srvRecordPort);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
+ ": using values from dns " + srvRecordServer
+ "[" + srvIpServer + "]:" + srvRecordPort);
} else {
addr = new InetSocketAddress(srvRecordServer, srvRecordPort);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
+ ": using values from dns "
+ srvRecordServer + ":" + srvRecordPort);
}
socket = new Socket();
socket.connect(addr, 20000);
socketError = false;
} catch (final UnknownHostException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
i++;
} catch (final IOException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
i++;
}
}
if (socketError) {
throw new UnknownHostException();
}
} else if (result.containsKey("error")
&& "nosrv".equals(result.getString("error", null))) {
//todo:change here to server.
socket = new Socket(server_ip, server port);
} else {
throw new IOException("timeout in dns");
}
final OutputStream out = socket.getOutputStream();
tagWriter.setOutputStream(out);
final InputStream in = socket.getInputStream();
tagReader.setInputStream(in);
tagWriter.beginDocument();
sendStartStream();
Tag nextTag;
while ((nextTag = tagReader.readTag()) != null) {
if (nextTag.isStart("stream")) {
processStream(nextTag);
break;
} else {
throw new IOException("unknown tag on connect");
}
}
if (socket.isConnected()) {
socket.close();
}
} catch (final UnknownHostException | ConnectException e) {
this.changeStatus(Account.State.SERVER_NOT_FOUND);
} catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
this.changeStatus(Account.State.OFFLINE);
} finally {
if (wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (final RuntimeException ignored) {
}
}
}
}
enjoy your code:)

Server side auto disconnect user connection and array index outofbounds error

server will run the array which disconnect user after client press connect button
public void run() {
String message, connect = "Connect", disconnect = "Disconnect", chat = "Chat" ;
String[] data;
try {
while ((message = reader.readLine()) != null) {
outputTextArea.append("Received: " + message + "\n");
data = message.split(":");
for (String token:data) {
outputTextArea.append(token + "\n");
}
if (data[2].equals(connect)) {
tellEveryone((data[0] + ":" + data[1] + ":" + chat));
userAdd(data[0]);
} else if (data[2].equals(disconnect)) {
tellEveryone((data[0] + ":has disconnected." + ":" + chat));
userRemove(data[0]);
} else if (data[2].equals(chat)) {
tellEveryone(message);
} else {
outputTextArea.append("No Conditions were met. \n");
}
} // end while
} // end try
catch (Exception ex) {
outputTextArea.append("Lost a connection. \n");
ex.printStackTrace();
clientOutputStreams.remove(client);
} // end catch
} // end run()
} // end class ClientHandler
public void userAdd (String data) {
String message, add = ": :Connect", done = "Server: :Done", name = data;
outputTextArea.append("Before " + name + " added. \n");
onlineUsers.add(name);
outputTextArea.append("After " + name + " added. \n");
String[] tempList = new String[(onlineUsers.size())];
onlineUsers.toArray(tempList);
for (String token:tempList) {
message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}
public void userRemove (String data) {
String message, add = ": :Connect", done = "Server: :Done", name = data;
onlineUsers.remove(name);
String[] tempList = new String[(onlineUsers.size())];
onlineUsers.toArray(tempList);
for (String token:tempList) {
message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}
public void tellEveryone(String message) {
// sends message to everyone connected to server
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
outputTextArea.setCaretPosition(outputTextArea.getDocument().getLength());
} // end try
catch (Exception ex) {
outputTextArea.append("Error telling everyone. \n");
} // end catch
} // end while
} // end tellEveryone()
Client Side:
ArrayList<String> userlist = new ArrayList();
public class IncomingReader implements Runnable{
public void run(){
String stream;
String[] data;
String done = "Done", connect = "connect", disconnect = "Disconnect", chat ="Chat";
try {
while ((stream = reader.readLine()) != null){
data = stream.split("!");
if (data[2].equals(chat)) {
chatTextArea.append(data[0]+":"+ data[1]+"\n");
chatTextArea.setCaretPosition(chatTextArea.getDocument().getLength());
} else if (data[2].equals(connect)){
chatTextArea.removeAll();
userAdd(data[0]);
} else if (data[2].equals(disconnect)){
userRemove(data[0]);
} else if (data[2].equals(done)){
onlineuserlist.setText("");
writeUsers();
userlist.clear();
}
}
}catch(Exception ex){
}
}
}
private void userAdd(String data) {
userlist.add(data);
}
private void userRemove(String data) {
chatTextArea.append(data +"has disconnected.\n");
}
private void writeUsers() {
String[] tempList = new String[(userlist.size())];
userlist.toArray(tempList);
for (String token:tempList) {
onlineuserlist.append(token +"\n");
}
}
public void sendDisconnect(){
String bye =(username + ": :Disconnect");
try{
writer.println(bye);
writer.flush();
} catch (Exception ex){
chatTextArea.append("could not send Disconnect Message.\n");
}
}
public void Disconnect(){
try{
chatTextArea.append("Disconnected.\n");
sock.close();
} catch (Exception ex){
chatTextArea.append("Failed to disconnect. \n");
}
isConnected = false;
usernameField.setEditable(true);
onlineuserlist.setText("");
}
}
after start the server and client press the connect button, it will show which user has connected but it also disconnect the connection and got this error.
java.lang.ArrayIndexOutOfBoundsException: 2
at chatsystemserver.ServerSide$ClientHandler.run(ServerSide.java:55)
at java.lang.Thread.run(Thread.java:745)
It would appear that you don't have an array of size == 3 when you do you split. You might want to do some array size checking before you access "data[2]".

java chat program via internet [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
well, what i want to do is basically, to make a client server chat program that works over internet, ive done a basic one that works flawlessly over lan, but cant get it right over the internet..
Server :
public class Server extends javax.swing.JFrame {
HashMap<String,PrintWriter> map = new HashMap<String,PrintWriter>();
ArrayList clientOutputStreams = new ArrayList();
ArrayList<String> onlineUsers = new ArrayList();
int port = 5080;
Socket clientSock = null;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
PrintWriter client;
public ClientHandler(Socket clientSocket, PrintWriter user) {
// new inputStreamReader and then add it to a BufferedReader
client = user;
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
System.out.println("first");
} // end try
catch (Exception ex) {
System.out.println("error beginning StreamReader");
} // end catch
} // end ClientHandler()
#Override
public void run() {
System.out.println("run method is running");
String message;
String[] data;
String connect = "Connect";
String disconnect = "Disconnect";
String chat = "Chat";
try {
while ((message = reader.readLine()) != null) {
ta1.append(message + "\n");
ta1.repaint();
System.out.println("Received: " + message);
data = message.split("#");
for (String token : data) {
System.out.println(token);
}
System.out.println(data[data.length - 1] + " datalast");
if (data[2].equals(connect)) {
tellEveryone((data[0] + "#" + data[1] + "#" + chat));
userAdd(data[0]);
map.put(data[0], client);
} else if (data[2].equals(disconnect)) {
System.out.println("barpppppppppp");
tellEveryone((data[0] + "#has disconnected." + "#" + chat));
userRemove(data[0]);
map.remove(data[0]);
} else if (data[2].equals(chat)) {
tellEveryone(message);
} else {
System.out.println("No Conditions were met.");
}
} // end while
} // end try
catch (Exception ex) {
System.out.println("lost a connection");
System.out.println(ex.getMessage());
clientOutputStreams.remove(client);
} // end catch
} // end run()
}
public void go() {
// clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(port);
System.out.println("ServerSocket Created !");
System.out.println("Started listening to port " + port);
while (true) {
// set up the server writer function and then begin at the same
// the listener using the Runnable and Thread
clientSock = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
ta1.append(writer + " ");
ta1.repaint();
System.out.println(writer);
clientOutputStreams.add(writer);
//data_of_names_and_output_streams.add(writer.toString());
// use a Runnable to start a 'second main method that will run
// the listener
Thread listener = new Thread(new Server.ClientHandler(clientSock, writer));
listener.start();
System.out.println("Server Thread for 'new player' was started");
System.out.println("got a connection");
} // end while
} // end try
catch (Exception ex) {
System.out.println("error making a connection");
} // end catch
} // end go()
public void userAdd(String data) {
String message;
String add = "# #Connect", done = "Server# #Done";
onlineUsers.add(data);
String[] tempList = new String[(onlineUsers.size())];
onlineUsers.toArray(tempList);
for (String token : tempList) {
message = (token + add);
tellEveryone(message);
System.out.println(message);
}
tellEveryone(done);
}
public void userRemove(String data) {
System.out.println(onlineUsers.size() + " is size of online users");
System.out.println(clientOutputStreams.size() + " is size of ous");
String message;
String add = "# #Connect", done = "Server# #Done";
onlineUsers.remove(data);
String[] tempList = new String[(onlineUsers.size())];
onlineUsers.toArray(tempList);
for (String token : tempList) {
message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}
public void tellEveryone(String message) {
System.out.println(onlineUsers.size() + " is size of online users");
System.out.println(clientOutputStreams.size() + " is size of ous");
// jButton1.doClick();
// sends message to everyone connected to server
Iterator it = clientOutputStreams.iterator();
if (message.length() < 250) {
System.out.println("inside it");
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
// l1.setText(message);
System.out.println("Sending " + message);
writer.flush();
} // end try
catch (Exception ex) {
System.out.println("error telling everyone");
} // end catch
}
} else {
try {
clientSock.close();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* Creates new form Server
*/
public Server() {
initComponents();
ta1.repaint();
}
public static void main(String args[]) throws Exception {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Server().setVisible(true);
}
});
new Server().go();
}
} //end form
Client : jbutton1 is setting up connection,jbutton2 sends the message.
public class Client extends javax.swing.JFrame {
boolean sent, receive;
SimpleDateFormat sdf;
String ip;
String username;
Socket sock;
BufferedReader reader;
PrintWriter writer;
ArrayList<String> userList = new ArrayList();
Boolean isConnected = false;
DefaultListModel dlm;
public Client() {
initComponents();
dlm = (DefaultListModel) l1.getModel();
ip = JOptionPane.showInputDialog("Enter the IP of the server to connect");
}
public class IncomingReader implements Runnable {
public void run() {
String stream;
String[] data;
String done = "Done", connect = "Connect", disconnect = "Disconnect", chat = "Chat", battlerequest = "battlerequest";
try {
while ((stream = reader.readLine()) != null) {
data = stream.split("#");
System.out.println(stream + " ------------------------ data");
if (data[2].equals(chat)) {
sdf = new SimpleDateFormat("HH:mm:ss");
t.append("(" + sdf.format(new Date()) + ") " + data[0] + ": " + data[1] + "\n");
//t.setText("<html><b>hi" + 3 + 3 + "</b></html>");
} else if (data[2].equals(connect)) {
t.removeAll();
userAdd(data[0]);
} else if (data[2].equals(disconnect)) {
userRemove(data[0]);
} else if (data[2].equals(done)) {
dlm.removeAllElements();
writeUsers();
userList.clear();
} else {
System.out.println("no condition met - " + stream);
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage() + " hi");
}
}
}
public void ListenThread() {
Thread IncomingReader = new Thread(new Client.IncomingReader());
IncomingReader.start();
}
public void userAdd(String data) {
userList.add(data);
}
public void userRemove(String data) {
t.setText(t1.getText() + data + " has disconnected.\n");
}
public void writeUsers() {
String[] tempList = new String[(userList.size())];
userList.toArray(tempList);
for (String token : tempList) {
//ul.append( token + "\n");
dlm.addElement(token);
// ul.setText(ul.getText() + token + '\n');
}
}
public void sendDisconnect() {
String bye = (username + "# #Disconnect");
try {
writer.println(bye); // Sends server the disconnect signal.
writer.flush(); // flushes the buffer
} catch (Exception e) {
t.append("Could not send Disconnect message.\n");
}
}
public void Disconnect() {
try {
t.append("Disconnected.\n");
sock.close();
} catch (Exception ex) {
t.append("Failed to disconnect. \n");
}
isConnected = false;
n.setEditable(true);
dlm.removeAllElements();
// ul.setText("");
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (isConnected == false && !n.getText().equals("")) {
username = n.getText();
n.setEditable(false);
try {
sock = new Socket(ip, 5080);
InputStreamReader streamreader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(sock.getOutputStream());
writer.println(username + "#has connected.#Connect"); // Displays to everyone that user connected.
writer.flush(); // flushes the buffer
isConnected = true;
jLabel4.setText(n.getText());
//t.append( "<html><font color = \"black\"><b>Server : Welcome,</b></font></html>"+username);
//t1.setText("<html><font color=\"red\">yo</font></html>");
// Used to see if the client is connected.
} catch (Exception ex) {
t.append("Cannot Connect! Try Again. \n");
n.setEditable(true);
}
ListenThread();
} else if (isConnected == true) {
t.append("You are already connected. \n");
} else if (n.getText().equals("")) {
t.append("Enter a valid name \n");
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String nothing = "";
if ((t1.getText()).equals(nothing)) {
t1.setText("");
t1.requestFocus();
} else {
try {
writer.println(username + "#" + t1.getText() + "#" + "Chat");
writer.flush(); // flushes the buffer
} catch (Exception ex) {
t.append("Message was not sent. \n");
}
t1.setText("");
t1.requestFocus();
}
t1.setText("");
t1.requestFocus(); // TODO add your handling code here:
}
private void dicsActionPerformed(java.awt.event.ActionEvent evt) {
sendDisconnect();
Disconnect(); // TODO add your handling code here:
}
i have also port forwarded the ports i am going to use - ie. 5080
now when my friend opens the client program from his computer from his home, i tell him to enter the ip as 192.168.1.2 coz thats what is saved when i open cmd and type ipconfig....
sometimes i think that the ip address i gave him is wrong coz 192.168.1.2 is i guess lan or internal ip address, so then, so do i do ? where do i get the correct ip address ? or is something else wrong in my code ?
192.168.1.2 is a non-routable IP. Click here to get your current external IP (unless your IP address is static, it may change periodically).
If you were to sign up for a dynamic dns service (here for example), then you could give your friend a "domain name" (e.g. something.dnsdynamic.com) and the service would update when your IP address changes.

How to connect and disconnect to/from FTP server correctly?

I'm wondering if the way that I connect and disconnect to/from a FTP server is correct or if it can be better.
I'm using sun.net.ftp.FtpClient.
import sun.net.ftp.FtpClient;
public class FTPUtility
{
public static FtpClient connect(FTPConfig ftpConfig,WebTextArea statusTextArea)
{
String hostname = ftpConfig.getFtpServer();
String username = ftpConfig.getUsername();
String password = ftpConfig.getPassword();
String portnumb = ftpConfig.getPort();
try
{
FtpClient client = new FtpClient(hostname);
statusTextArea.append("Connecting to " + hostname + " as " + username + " on port:" + portnumb );
client.login(username, password);
client.binary();
statusTextArea.append("Connected to " + hostname + " as " + username + " on port:" + portnumb );
return client;
}
catch (Exception e)
{
statusTextArea.append("Failed to connect to " + hostname + " as " + username + "\n".concat(e.getMessage()) );
return null;
}
}
public static boolean disConnect(FtpClient client, WebTextArea statusTextArea)
{
boolean success = false;
if (client != null)
{
try
{
statusTextArea.append("Disconnecting from server...");
client.closeServer();
statusTextArea.append("Disconnected from server." );
success = true;
}
catch (Exception e)
{
statusTextArea.append("Failed to disconnect from server. " + "\n".concat(e.getMessage()));
}
}
return success;
}
}
If we look at the documentation it shows using logout() and disconnect()
I would also suggestion a better naming convention for your method name disConnect which should just be disconnect(FtpClient client, WebTextArea statusTextArea) (no capital C)
boolean error = false;
try {
int reply;
ftp.connect("ftp.foobar.com");
System.out.println("Connected to " + server + ".");
System.out.print(ftp.getReplyString());
// After connection attempt, you should check the reply code to verify
// success.
reply = ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
System.exit(1);
}
... // transfer files
ftp.logout();
} catch(IOException e) {
error = true;
e.printStackTrace();
} finally {
if(ftp.isConnected()) {
try {
ftp.disconnect();
} catch(IOException ioe) {
// do nothing
}
}
System.exit(error ? 1 : 0);
}
Also return false if the closing fails
catch (Exception e)
{
statusTextArea.append("Failed to disconnect from server. " + "\n".concat(e.getMessage()));
return false;
}
}
You might want to check out the FtpClient from apache commons project:
FtpClient.
The javaDoc contains some well worked out examples.

Categories

Resources