Program does not read messages (Twitch IRC) - java

I made a ReadMessage thread that should run in the background and read messages when they come in. This is how it looks:
Thread ReadMessages = new Thread(new Runnable() {
public void run() {
try {
while(socket.isConnected()){
ServerMsg = in.readLine();
jTextArea1.append(ServerMsg);
}
} catch (IOException ex) {
System.out.println("Something went wrong! THREAD");
}
}
});
I start it everytime i start my program:
public TwitchBotFenster() throws IOException, Exception {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
initComponents();
ReadMessages.start();
}
The problem I have, is that it only reads the first messages when I connect to twitch irc but if I write something in the chat it doesnt. I dont really get the problem. My thoughts when I made that were, whenever the socket is connected it should read all the messages.
EDIT:
This is how i send messages to the server:
public void SendMessage() throws IOException{
try{
if(BotName == null){
this.jTextArea1.append("You are not logged in!\n");
}else{
this.ClientChatMessage = this.jTextField4.getText();
out.write(":" + BotName + "!" + BotName + "#" + BotName + ".tmi.twitch.tv PRIVMSG #" + this.Channelname + " :" + this.ClientChatMessage + "\n");
out.flush();
this.jTextField4.setText("");
this.jTextArea1.append("*" + BotName + ">> " + ClientChatMessage + "\n");
}
this.jTextField4.setText("");
}catch(Exception exe){
System.out.println("Something went horribly wrong! (SendMessage/func)\n");
}
}
EDIT2:
Messages are sent whenever i press enter in my jTextField:
private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {
try {
SendMessage();
} catch (IOException ex) {
System.out.println("Something went horribly wrong! (SendMessage)\n");
}
}

Related

Using JavaOsc to get meter readings from a Behringer X32

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!

How can loop continue before method is finished?

I have multiple threads(runnables) in my program. On of theme is handling RS232 communication.
My problem is that code inside the loop is not executed in the order that is written:
while(!serialData.dataToSend.isEmpty())
{
try {
SerialMsgToSend msgObject = serialData.dataToSend.remove();
if(msgObject.type == msgObject.HOLDING_REGISTER)
{
Thread.sleep(COMMAND_WAIT_TIME);
Toolkit.getDefaultToolkit().beep();
modBusManager.singleRegisterWriteToMultipleRegisters(msgObject.unit, msgObject.startRegisterAdress, msgObject.data);
}
else if(msgObject.type == msgObject.COIL)
{
Thread.sleep(COMMAND_WAIT_TIME);
Toolkit.getDefaultToolkit().beep();
modBusManager.writeToCoil(msgObject.unit, msgObject.startRegisterAdress, msgObject.data[0] == 1);
}
Thread.sleep(5000);
readUnitsData(msgObject.unit);
Thread.sleep(5000);
if(msgObject.RESPONSE > 0)
{
serialData.listeners[msgObject.unit - 1].sendResponseToServer(msgObject.RESPONSE);
}
} catch (Exception ex) {
log.error("Exception on sending data: " + ex.toString());
}
}
First I write to ModBus register with calling:
modBusManager.singleRegisterWriteToMultipleRegisters(msgObject.unit, msgObject.startRegisterAdress, msgObject.data);
After that I want to wait 5 seconds that registers are updated, then read them and send information to server.
I read the data with calling method:
readUnitsData(msgObject.unit);
And then I am using listener to tell another thread to send data to server:
serialData.listeners[msgObject.unit - 1].sendResponseToServer(msgObject.RESPONSE);
My problem is that data is sent to server before it gets read/updated so I send old data. I am used that code is executed in the order that is written. Am I using threads in a wrong way or what could be the problem?
Here is method which I call to read data:
private void readUnitsData(int unitID)
{
if(mtxData.climatList[unitID] != null)
{
try
{
log.info("Serial reading data for: " + unitID);
int[] coils = modBusManager.readCoils(unitID + 1,0,87);
String[] holding = modBusManager.readHoldingRegisters(unitID + 1,0,64); //(int slaveAdress, int registerAdress, int registerQuntaity)
if(coils != null && holding != null)
{
System.out.println("send to listner: " + unitID);
serialData.listeners[unitID].newHoldingAndCoilData(holding, coils);
}
} catch (Exception ex)
{
log.error("Exception on run: " + ex.toString());
}
}
}
And method inside other runnable, which is connected to listener:
#Override
public void sendResponseToServer(int responseType)
{
try
{
log.info("listener for sendStatusToServer called: " + responseType);
Thread.sleep(15000);
switch(responseType)
{
case 1:
communicationManager.sendStatus();
break;
case 2:
communicationManager.sendSettings();
break;
}
}catch(Exception ex)
{
log.error("Exception on sendResponseToServer: " + ex);
}
}
I did like #Markus Mitterauer proposed and took apart the code. I found that that it was problem with one of the unitID's which was wrong. Because of that I didn't get any values when reading registers and listener wasn't triggered correctly.

Have to enter something twice in scanner when using thread - Java

For some reason, I have to enter something twice for it to print out in Java when Using Scanner in a thread. I dont know why this is, but IT is very annoying. Because of this, My message sends through the socket and gets to the other person but does not show it to the person sending it, but on the second try it shows to the person who sent it but it doesnt get to the person that should receive it!
(If something doesnt look like its from the Java API, its because its a Test Class for My API)
Note: The code is the exact same on both sides, except they use different ports.
private static UDPSocket TestUDP;
private static String Username = "9843";
public static void main(String[] args) {
try {
TestUDP = new UDPSocket(9844);
TestUDP.defineDefaultAddress("localhost", 9843);
Username = "Lawton";
System.out.println("You set your name to: " + Username);
new Thread(new Receive()).start();
new Thread(new Send()).start();
} catch (Exception e) {
e.printStackTrace();
}
}
static class Send implements Runnable {
public void run() {
try {
while (true) {
Scanner UserInput = new Scanner(System.in);
TestUDP.send("0x00", Username + ": " + UserInput.nextLine());
System.out.println(Username + ": " + UserInput.nextLine());
Thread.sleep(1);
}
} catch (Exception E) {
System.err.println("There was a error.");
}
}
}
static class Receive implements Runnable {
public void run() {
try {
while (true) {
byte[] Message = TestUDP.receive();
System.out.println(Packet.decrypt(Message));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use a variable to avoid calling scanner.nextLine() twice:
Scanner UserInput = new Scanner(System.in);
String readUsername = UserInput.nextLine();
TestUDP.send("0x00", Username + ": " + readUsername);
System.out.println(Username + ": " + readUsername);

How to make server and client in java?

I i am making a server/client but there seems to be a problem. I cannot seem to connect when i click the button.Please help.Not sure what i did wrong.Feel free to edit code to fix it then comment please.I have a connect button,and a send button. I think it has something to do with the highlighted code but it could be anything. I know this isnt very specific but basically heres the code and it doesnt work. I cant connect . please help!
Client
public class chat_client extends javax.swing.JFrame {
String username;
Socket sock;
BufferedReader reader;
PrintWriter writer;
ArrayList<String>userList = new ArrayList();
Boolean isConnected = false;
public chat_client() {
initComponents();
getContentPane().setBackground(Color.white);
this.setIconImage(new ImageIcon(getClass()
.getResource("dogeIcon.jpg")).getImage());
this.setLocationRelativeTo(null);
}
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)){
txtChat.append(data[0] + ":" + data[1] + "\n");
} else if (data[2].equals(connect)){
txtChat.removeAll();
userAdd(data[0]);
} else if (data[2].equals(disconnect)){
userRemove(data[0]);
} else if (data[2].equals(done)){
userList.setText("");
writeUsers();
}
} catch(Exception ex){
}
}
}
public void ListenThread(){
Thread IncomingReader = new Thread(new IncomingReader());
IncomingReader.start();
}
public void userAdd(String data){
userList.add(data);
}
public void userRemove(String data){
txtChat.append(data + " has disconnected \n");
}
public void writeUsers(){
String[] tempList = new String[(userList.size())];
userList.toArray(tempList);
for (String token:tempList){
userList.append(token + "\n");
}
}
public void sendDisconnect(){
String bye = (username + "^ ^Disconnected");
try{
writer.println(bye);
writer.flush();
} catch(Exception e){
txtChat.append("Could Not Send Disconnect Message \n");
}
}
public void Disconnect(){
try{
txtChat.append("Disconnected\n");
sock.close();
} catch(Exception ex){
txtChat.append("Failed to disconnect\n");
}
isConnected = false;
txtUser.setEditable(true);
userList.setText("");
}
(This is the highlighted part where i think the problem is)
***private void connectActionPerformed(java.awt.event.ActionEvent evt) {
if (isConnected == false){
username = txtUser.getText();
txtUser.setEditable(false);
try{
sock = new Socket("localhost", 1023);
InputStreamReader streamreader
= new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(sock.getOutputStream());
writer.println(username + "^has connected.^Connect");
writer.flush();
isConnected = true;
} catch(Exception ex){
txtChat.append("Cannot Connect! Try Again\n");
txtUser.setEditable(true);
}
ListenThread();
} else if (isConnected == true){
txtChat.append("You is connected bra\n");
}
}***
(Ends here-the problem/highlighted part)
private void btn_SendActionPerformed(java.awt.event.ActionEvent evt) {
String nothing = "";
if ((txtMsg.getText()).equals(nothing)){
txtMsg.setText("");
txtMsg.requestFocus();
} else {
try{
writer.println(username + "^" + txtMsg.getText() + "^"
+ "Chat");
writer.flush();
} catch (Exception ex){
txtChat.append("Message was not sent\n");
}
txtMsg.setText("");
txtMsg.requestFocus();
}
A couple things:
You're getting a java.net.ConnectionException (see below) because the connection is being refused. This could be because the server you are trying to connect to is not running, the server is not accepting client connections, the server is not accessible by the client, or you are connecting to the wrong port number.
It is generally bad coding practice to catch Exception directly. You want to either catch the most specific exception that ranges across the variety of exceptions that can be thrown (in this case, IOException) or catch each possible one individually, which is the preferred method. Catch the most specific exceptions before the more general ones so that they are not masked by them. Furthermore it is a good idea to use the Throwable class's getMessage() method so that you can figure out the reason for the exception being thrown. For example:
} catch (java.net.ConnectException ex) {
System.err.println("ConnectException: " + ex.getMessage()); // May return "Connection refused", "Connection timed out", "Connection reset", etc.
} catch (java.rmi.UnknownHostException ex) {
System.err.println("UnknownHostException: " + ex.getMessage()); // Returns the name of the host you were attempting to connect to
} catch (...) {
// code here
} catch (java.io.IOException ex) {
System.err.println("IOException: " + ex.getMessage()); // May return a problem with the BufferedReader or InputStreamReader or PrintWriter
}
Of course, the statements in the catch clause can be modified to your liking.

Full-duplex server socket implementaion, seperate read and write thread?

I want to read and write(randomly from server to client) on same server socket (java application). My client to server write and read work fine in a loop. At server with response write properly.
But if i am trying to write at server randomly some command. i do not have solution, first of all my question is :
is it possible at server side to write command to client ramdonly on same socket?
if possible, any suggestion or pointer how to do it?
please give me some pointer where I can read the material about this scenario ?
thanks in advance.
public class ContentServerSocket extends ServerSocket {
private final static int PORT = 4444;
protected static boolean XYZGONE = false;
public static Content content;
public ContentServerSocket(xyzService service) throws IOException {
super(PORT);
while (true) {
Log.d(TAG, "Waiting for new request from client(content) ....");
new HandleRequest(accept(), service).start();
}
}
public static void xyzRunAway() {
Log.d(TAG," Content Serv er 1 ");
XYZGONE = true;
}
}
class HandleRequest extends Thread {
private final static String TAG = "ContentServerSocket:Thread for a request:";
private Socket client;
private xyzService service;
private static Context context;
HandleRequest(Socket client, SuggestionService service) {
this.client = client;
this.service = service;
context = xyzService.serviceContext();
}
public void run() {
while (true) {
try {
Log.d(TAG, " Step 1: client: Received request MSG for Check... ");
PrintWriter out = new PrintWriter(client.getOutputStream(),
true);
BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream(), "utf-8"));
String request = "";
String tmpLine = null;
Log.d(TAG, " Step Xyz waiting data from the client ... ");
while ((tmpLine = in.readLine()) != null) {
if (tmpLine.length() > 0) {
request += tmpLine;
//if (tmpLine.toLowerCase().contains("</contentInfo>")) {
if (tmpLine.contains("</contentInfo>")) {
Log.d(TAG, " Server : broke because of </contentInfo>");
break;
}
} else {
Log.d(TAG, " Step NULL : ");
request = "";
}
}
Log.d("Robin", " Step 2: Actual request received from the client : : " + request);
if (request.length() == 0) {
Log.d("Robin",
" client got 0 length request, thread stop!");
throw new Exception();
}
//XMLParser xmlParser = new XMLParser(new ByteArrayInputStream(
// request.getBytes("UTF-8")));
Log.d(TAG, " Step 3 : ");
RequestParser readxmlrequest = new RequestParser(request);
String requestType = readxmlrequest.parsingXmlRequestFromContent();
Log.d(TAG, " Step 4 requestType : " + requestType);
//TODO : need to get the result and pas to the out.println..
//String result = processXML(xmlParser);
String result = responseToContentRequest(readxmlrequest,requestType);//null; //TODO need to complete.
Log.d(TAG, " Step 5 result : "+result);
(((((((((())))))))))";
if (result != null && result.length() > 0) {
//oos.writeObject(result);
Log.d("Robin", " Writing response to socket ... ");
out.println(result + "\n");
out.flush();
Log.d("Robin", " Writing flush completed ");
}
if(ContentServerSocket.XYZGONE) {
Log.d(TAG," XYZGONE >>>>>>>> ");
ContentServerSocket.XYZGONE = false;
String tmp = "<ssr> OK Done .......</ssr>";
out.println(tmp + "\n");
Log.d("Content Server Socket ", "xyz:" + tmp);
out.flush();
}
} catch (IOException ioException) {
Log.d("Robin", " IOException on socket listen: " + ioException);
}
catch (Exception e) {
Log.d("Robin", " outer exception: " + e.toString());
break;
}
finally {
if (client == null || client.isClosed()
|| !client.isConnected()) {
Log.d(" Robin ", " client is null");
break;
}
}
//break;
}
Log.d("Robin", " thread stop... ");
}
So , I fixed it . I just need to maintain two different thread.
1) read.
2)write.
In the above code i just started one more thread for write .
insert the code in Run function of above code.
====================================================
Runnable r1 = new Runnable() {
public void run() {
try {
while (true) {
System.out.println("Hello, world!");
if(ContentServerSocket.XYZGONE) {
Log.d(TAG," XYZGONEY >>>>>>>> ");
ContentServerSocket.XYZGONE = false;
String tmp = "<ssr> OK Done .......</ssr>";
out.println(tmp + "\n");
Log.d("Content Server Socket ", "XYZGONE :" + tmp);
out.flush();
}
Thread.sleep(1000L);
}
} catch (InterruptedException iex) {}
}
};
Thread thr1 = new Thread(r1);
==================================
Then Start the thread in the wile loop of read.
with the following code with a check.
====================================
if(!thr1.isAlive())thr1.start();
Thanks everyone, who respond my question..
Yes it is possible to write data from multiple threads on a server or on a client to an existing socket. However you have to make sure the requests do not overlap, and the receiving side actually knows what is written from who.
If you use a line based protocol you can define each message is a single line. In that case you should synchronize multiple threads in a way that only one is writing parts of that line at any given moment.
Your code is a bit too big to understand where your problem is, sorry.
Maybe this tutorial helps? There are quite many out there:
http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets.html

Categories

Resources