I'm making Chatting-Room program using the Java Swing.
In the client side, I was saw that doesn't read message from the server side.
The writeUTF() method of the client side is very well and I'm checked readUTF and writeUTF on the server side, that was very well too.
I think the problem is code which does as "Receiver" on the client side.
In the run() method of Thread, The instance dis of the DataInputStream has continuously null value.
I'm so confusing.. Please give me some help.
The bellow is part of my client&server code.
Thanks!
Client code
RoomBackground.java
public class RoomBackground {
private static String socket_server = "127.0.0.1";
private static Socket chatSocket;
private static DataOutputStream dos;
private static DataInputStream dis;
private ChatReceiver chatReceiver;
public Socket getChatSocket() {
return chatSocket;
}
public static DataOutputStream getDos() {
return dos;
}
public RoomBackground() throws IOException {
chatSocket = new Socket(socket_server, 7777);
chatReceiver = new ChatReceiver();
chatReceiver.start();
dos = new DataOutputStream(chatSocket.getOutputStream());
dis = new DataInputStream(chatSocket.getInputStream());
dos.writeUTF(User.getUser().getUsername());
dos.flush();
}
class ChatReceiver extends Thread {
#Override
public void run(){
try {
# PROBLEM CODE..... Allways "dis is null"
System.out.println("dis is " + dis);
# This line never executed.
while(dis != null) {
# some codes.....
}
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.toString());
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
RoomFrame.java
public class RoomFrame extends JFrame{
private RoomBackground roomBackground;
public RoomFrame(int roomId) throws IOException {
chatField.addActionListener(new ActionListener() {
roomBackground = new RoomBackground();
#Override
public void actionPerformed(ActionEvent e) {
String msg = chatField.getText() + "\n";
try {
RoomBackground.getDos().writeUTF(msg);
# It works.
System.out.println("sent msg is " + msg);
} catch (IOException e1) {
e1.printStackTrace();
}
chatField.setText("");
}
});
}
}
Now server code.
Server Background.java
public class ChatReceiver extends Thread {
private DataInputStream in;
private DataOutputStream out;
public ChatReceiver(Socket chatSocket) throws IOException {
out = new DataOutputStream(chatSocket.getOutputStream());
in = new DataInputStream(chatSocket.getInputStream());
nick = in.readUTF();
addChatClient(nick, out);
}
#Override
public void run() {
try {
while(in!=null) {
chatMsg = in.readUTF();
# It works !
System.out.println("before send" + chatMsg);
sendMsg(chatMsg);
# It works too!
System.out.println("after send" + chatMsg);
}
}catch (IOException e) {
removeChatClient(nick);
}
}
}
When you are starting the ChatReceiver thread in the RoomBackground the dis object is not initialized yet, that is why it is null. One solution could be to initialize the dis variable in the ChatReceiver constructor.
Related
This is the simple client/server socket app for my faculty project. First, the Server class should be run, and then if Client class runs - it prints out the IP address of the local machine and the port that's been used.
I can't figure out one thing:
How and WHERE to create a method in class that will close(stop) the Server? And
how to make this like an event or something, for example if client
sends "stop" it should somehow stop the server...
SERVER.JAVA
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
System.out.println("The server has been summoned.\n");
System.out.println("The server is waiting for client to come...");
try {
ServerSocket servertest = new ServerSocket(2014);
while (true) {
try {
Socket ser = servertest.accept();
new ThreadSer(ser).start();
} catch (IOException e) {}
}
} catch (IOException e) {System.err.println(e);}
}
public static class ThreadSer extends Thread {
private Socket s;
public ThreadSer(Socket s) {
this.s = s;
}
#Override
public void run() {
try {
String response = "This is the IP: " + s.getLocalAddress() + " that has come via port: "
+ s.getLocalPort() + "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
} catch (IOException e) { System.err.println(e); }
}}}
CLIENT.JAVA
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 2014);
new OutputThread(socket.getInputStream()).start();
}
public static class OutputThread extends Thread {
private InputStream inputstream;
public OutputThread(InputStream inputstream) {
this.inputstream = inputstream;
}
#Override
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(inputstream));
while (true) {
try {
String line = input.readLine();
System.out.println(line);
} catch (IOException exception) {
exception.printStackTrace();
break;
}
}
}}}
You should constantly ask for the inputstream of the client.. put it in the loop that always accept for the client input..
example:
public static class ThreadSer extends Thread {
private Socket s;
public ThreadSer(Socket s) {
this.s = s;
}
#Override
public void run() {
try {
String response = "This is the IP: " + s.getLocalAddress() + " that has come via port: "
+ s.getLocalPort() + "\r\n";
ObjectInputStream input = new ObjectInputStream(s.getInputStream());
while(true)
{
Object object = input.readObject();
if(object instanceof String)
{
String command = ((String) object).trim();
if(command.equals("stop"))
break;
}
}
s.close();
} catch (IOException e) { System.err.println(e); }
}}}
I am using RXTX to communicate between JAVA and a microcontroller.
This is the JAVA code for opening a connection, sending and receiving data
package app;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SerialCommunication1 {
private static SerialCommunication1 instance = null;
private static boolean coonected = false;
public static SerialCommunication1 getInstance(){
if(instance == null)
instance = new SerialCommunication1();
return instance;
}
private SerialCommunication1() {
super();
try {
connect("COM4");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SerialCommunication1.coonected = true;
}
void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier
.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(),
2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialReader(in))).start();
(new Thread(new SerialWriter(out))).start();
} else {
System.out
.println("Error: Only serial ports are handled by this example.");
}
}
}
/** */
public static class SerialReader implements Runnable {
InputStream in;
public SerialReader(InputStream in) {
this.in = in;
}
public void run() {
byte[] buffer = new byte[1024];
int len = -1;
try {
while ((len = this.in.read(buffer)) > -1) {
System.out.print(new String(buffer, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/** */
public static class SerialWriter implements Runnable {
OutputStream out;
static String str = null;
public SerialWriter(OutputStream out) {
this.out = out;
}
public void run() {
System.out.println("Will try to execute");
try {
if(str.length() > 0){
this.out.write(str.getBytes());
str = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And this is the Java code that is calling when an event triggers
SerialCommunication1.getInstance();
if(ledStatus == true) {SerialCommunication1.SerialWriter.str = "4A01";}
else {SerialCommunication1.SerialWriter.str = "4A00";}
stopProcess();
And now the problem. I need to send a command to my microcontroller with the code 4A01 and, after receiving the answer, I need to call it again with the code 4A00. The calls are triggered by a button from my Java interface. The problem is that the second call is not executed (4A00 is not sending). I tried to inverse the command codes and they work well. After the first one (4A01) is executed, my microcontroller reacts and sends the response which is read by java and my interface is updated. When I send the invers command (4A00) it stops exactly at this line SerialCommunication1.SerialWriter.str = "4A00"; and doesn't even enter inside the SerialWriter's run() method.
Do you have any idea why is this happening? From the side of my microcontroller there is no problem, I checked all the possibilities with a tool.
I hope I made myself clear.
Thank you!
LE: I forgot to tel you that it didn't throw any errors or exceptions
I'm not sure because I'm not able to test your code but I think your problem is in SerialWriter class:
public static class SerialWriter implements Runnable {
OutputStream out;
static String str = null; // Here str is initialized to null
public SerialWriter(OutputStream out) {
this.out = out;
}
public void run() {
System.out.println("Will try to execute");
try {
if(str.length() > 0) { // this should throw NPE because str is null
this.out.write(str.getBytes());
str = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Since there is no loop in this method, then the thread created within SerialCommunication1 at this line:
(new Thread(new SerialWriter(out))).start();
most likely finishes its execution after sending the first str.
Honestly I don't understand how does it even send a single string, since str is initialized to null in first place and it should throw NullPointerException at str.length() line.
I would suggest you this approach:
Don't trigger a writer thread when connection is established, just trigger a new one every time a message will be sent.
Use Singleton pattern correctly.
Keep a reference to the serial port in SerialCommunication1 class.
Translated to code it would be something like this:
class SerialWriter implements Runnable {
OutputStream out;
String message;
public SerialWriter(OutputStream out) {
this.out = out;
}
public void setMessage(String msg) {
this.message = msg;
}
public void run() {
try {
if(message != null) {
this.out.write(str.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Then in SerialCommunication1 class add this public method:
public void sendMessage(String msg) {
SerialWriter writer = new SerialWriter(serialPort.getOutputStream()); // of course you'll have to keep reference to serialPort when connection is established
writer.setMessage(msg);
(new Thread(writer)).start();
}
And finally call this method in this way:
SerialCommunication1.getInstance().sendMessage("4A01");
tzortzik,
I think tha is a timeout problem. Try to addding a delay to writer :
/** */
public static class SerialWriter implements Runnable {
OutputStream out;
static String str = null;
public SerialWriter(OutputStream out) {
this.out = out;
}
public void run() {
Thread.sleep(500); //<----------- this should be in mainThread before to SerialWriter.start();
System.out.println("Will try to execute");
try {
if(str.length() > 0){
this.out.write(str.getBytes());
str = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It happens to me many times, "we should learn to wait for a response" (^_^)
Check if you are executing well a secuence like the next:
Send command 4A01
Receive response 4A01 from micro
WAIT FOR RESPONSE BEFORE SEND SECOND COMMAND. Thread.sleep(500); //wait for 500 milis or more
Send command 4A00
Receive response 4A00 from micro
I hope it could help you.
class SomeUI
{
SocketMessageSender messageSender;
// ensure that its initialized ...
private void bSendMessageActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
messageSender.sendMessage(jMessage.getText());
jMessage.setText("");
} catch (IOException ex) {
Logger.getLogger(TeKServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
ERROR: Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: bSendMessageActionPerformed
Why do you keep opening the socket and closing it on every button click. Create a class that allow you to keep the socket open for as long as your application run. The socket connection can be done when the application starts.You can try out the following class
public class SocketMessageSender
{
private String host;
private int port;
private DataOutputStream dos;
public SocketMessageSender(String host, int port)
{
this.host = host;
this.port = port;
}
// call when application starts
public void initConnection() throws IOException
{
InetAddress address = InetAddress.getByName(host);
Socket connection = new Socket(address, port);
dos = new DataOutputStream(connection.getOutputStream());
}
//call from button click
public void sendMessage(String message) throws IOException
{
if(dos != null)
{
dos.writeUTF(message);
dos.flush();
}
}
// call when application exits
public void closeConnection() throws IOException
{
if(dos!= null)
{
dos.close();
}
}
}
Hope it helps ...
Assume you have a class like
class SomeUI
{
SocketMessageSender messageSender;
// ensure that its initialized ...
private void bSendMessageActionPerformed(java.awt.event.ActionEvent evt) {
messageSender.sendMessage(jMessage.getText());
jMessage.setText("");
}
}
I think that the class signature should be something like this ....
public class MyPanel extends JPanel implements ActionListener
{
private SocketMessageSender messageSender;
private Message jMessage = new Message();// This is just a temp class, replace this with your class
public MyPanel()
{
messageSender = new SocketMessageSender("some host", 8080);
try
{
messageSender.initConnection();
}
catch(IOException e)
{
Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, e);
}
}
#Override
public void actionPerformed(ActionEvent e)
{
try {
// TODO add your handling code here:
messageSender.sendMessage(jMessage.getText());
jMessage.setText("");
} catch (IOException ex) {
Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Consider using ObjectOutputStream/ObjectInputStream and write object through sockets.
There are a lot of examples at java2s.com
Please mind that if you are writing same object multiple times, you will need to reset() stream before writing, and flush after it.
I am currently developing chat application working over Internet.currently my application working fine over LAN but not working over Internet.I have also used port forwarding.I have done setting in modem and forward the port to private IP address but still it's not working.I got the error that "server isn't found".Please suggest me what I have to do and tell,Am I done the correct setting in modem or not??
Below is my server code...
Server.java
import java.util.*;
import java.net.*;
import java.io.*;
class Server implements ChatConstants
{
private static Vector list;
private ServerSocket ssocket ;
private Service service;
private static Socket socket;
private boolean done=false;
private static Hashtable userTable = new Hashtable();
private static Hashtable _userList = new Hashtable();
private static Hashtable _conflist = new Hashtable();
public Server() throws UnknownHostException
{
System.out.println("Initializing...");
list=new Vector(BACKLOG);
try {
ssocket= new ServerSocket(SERVER_PORT,BACKLOG);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Inside constructor"+e);
}
start();
}
public void start() throws UnknownHostException
{
byte[] data;
int header;
Socket _socket = null;
String hostname = null;
System.out.println("Server successfully started at "
+InetAddress.getLocalHost().toString()
+" port "+SERVER_PORT);
while(!done) {
try
{
_socket=ssocket.accept();
if(_socket != null) {
synchronized(list) {
list.addElement(_socket);
}
DataInputStream dis=new DataInputStream(_socket.getInputStream());
data = new byte[MAX_MESSAGE_SIZE];
dis.read(data);
Message message = ((Message)ChatUtils.bytesToObject(data));
System.out.println("Joined client "
+message._username+" at "+message._host+"...");
synchronized(userTable) {
userTable.put(message._username,_socket);
}
addUser(message);
sendUserList(message);
writeToClients(message);
service = new Service(_socket,hostname,message._user);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Thread exception"+e);
try {
_socket.close();
}
catch(Exception ex) {
ex.printStackTrace();
System.out.println("ERROR CLOSING SOCKET");
}
}
}//END WHILE
}
private void addUser(Message message)
{
synchronized(_userList) {
_userList.put(message._user.toString(),message._user);
}
}
public static void updateUser(User user)
{
User myuser;
synchronized(_userList) {
_userList.put(user.toString(),user);
}
}
public static synchronized void writeToClients(Message message)
{
byte[] data;
DataOutputStream dos;
for(int count=0;count<list.size();count++) {
try {
dos=new
DataOutputStream(((Socket)list.elementAt(count)).getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Output exception");
}
}//END FOR
}
public static void writeToClient(Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(userTable) {
try {
socket = (Socket)userTable.get(message._destination);
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("SEND EXCEPTION"+e);
}
}
}
public static void sendConferenceListToClient(Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(userTable) {
try {
Message mymessage= new Message(CONFERENCE_LIST);
Vector vector = (Vector)
_conflist.get(message._destination);
mymessage._username = message._username;
mymessage._destination = message._destination;
mymessage.userlist = vector;
socket = (Socket)userTable.get(message._username);
if(socket!=null) {
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(mymessage);
dos.write(data,0,data.length);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("CONFERENCE LIST EXCEPTION"+e);
}
}
}
public static void writeToPublicChat(Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(_conflist) {
try {
Vector svector = (Vector)_conflist.get(message._destination);
for(int cnt=0;cnt<svector.size();cnt++) {
synchronized(userTable) {
try {
socket = (Socket)userTable.get((svector.get(cnt).toString()));
if(socket!=null) {
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("PUBLIC CHAT EXCEPTION"+e);
}
}
}
} catch(Exception e){
e.printStackTrace();
System.out.println("PUBLIC EXCEPTION"+e);
}
}
}
public static void inviteToPublicChat(Vector svector,Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(_conflist) {
for(int cnt=0;cnt<svector.size();cnt++) {
synchronized(userTable) {
try {
socket = (Socket)userTable.get((svector.get(cnt).toString()));
if(socket != null) {
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("PUBLIC INVITE EXCEPTION"+e);
}
}
}
}
}
private void sendUserList(Message message)
{
int header=0;
String destination;
header=message._header;
destination = message._destination;
message._header = USERS_LIST;
message._destination = message._username;
message.userlist = new Vector(_userList.values());
writeToClient(message);
//Restore the headers
message._destination = destination;
message._header = header;
}
public static synchronized void removeUser(User user)
{
try {
Socket socket = (Socket)userTable.get(user.toString());
list.removeElement(socket);
_userList.remove(user.toString());
userTable.remove(user.toString());
}
catch(Exception e) {
e.printStackTrace();
System.out.println("ERROR REMOVING SOCKET "+e);
}
}
public static synchronized void processClientMessage(Message message)
{
switch(message._header) {
case CHANGE_STATUS:
updateUser(message._user);
writeToClients(message);
break;
case CLIENT_LOGOUT:
removeUser(message._user);
writeToClients(message);
break;
case CONFERENCE_CREATE:
Vector myvector = new Vector();
myvector.add(message._username);
_conflist.put(message._user.toString(),myvector);
case CONFERENCE_INVITE:
inviteToPublicChat(message.userlist,message);
break;
case CONFERENCE_JOIN:
Vector vector=null;
vector = (Vector)
_conflist.get(message._destination.toString());
vector.add(message._username);
_conflist.put(message._destination.toString(),vector);
writeToPublicChat(message);
break;
case CONFERENCE_DENY:
//_conflist.remove(message._user.toString(),message.userlist);
writeToPublicChat(message);
break;
case CONFERENCE_LEAVE:
Vector vectors =(Vector)
_conflist.get(message._destination.toString());
for(int count=0;count<vectors.size();count++) {
if(message._username.equals((vectors.elementAt(count).toString())))
vectors.remove(count);
}
if(vectors.size() != 0)
_conflist.put(message._user.toString(),vectors);
else//IF THERE ARE NO MORE USERS
_conflist.remove(message._user.toString());//DONE CONFERENCE
writeToPublicChat(message);
break;
case PUBLIC_CHAT:
writeToPublicChat(message);
break;
case CONFERENCE_LIST:
sendConferenceListToClient(message);
break;
default:
writeToClient(message);
}
}
public static void main(String args[]) throws Exception
{
Server chatserver=new Server();
}
}
//
// Service: Service class for each clients connected to server.
//
class Service implements Runnable, ChatConstants
{
private DataInputStream dis;
private Socket socket;
private boolean done=false;
private Thread thread;
private String hostname;
private User user;
public Service(Socket _socket,String _hostname,User user)
{
try {
this.socket = _socket;
this.hostname=_hostname;
this.user = user;
dis=new DataInputStream(socket.getInputStream());
thread=new Thread(this,"SERVICE");
thread.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("service constructor"+e);
}
}
public void run()
{
byte[] data;
while(!done)
{
try {
data = new byte[MAX_MESSAGE_SIZE];
dis.read(data);
Message message = ((Message)ChatUtils.bytesToObject(data));
Server.processClientMessage(message);
}
catch(Exception e) {
e.printStackTrace();
done = true;
Server.removeUser(user);
Message message = new Message(CLIENT_LOGOUT);
user.isOnline = OFFLINE;
message._user = user;
Server.writeToClients(message);
try {
socket.close();
} catch(Exception se) {
se.printStackTrace();
System.out.println("ERROR CLOSING SOCKET "+se);
}
//System.out.println("SERVICE THREAD EXCEPTION"+e);
}
}//END WHILE
}
}
Thanks in advance.
I think the
ssocket= new ServerSocket(SERVER_PORT,BACKLOG);
is making the issue. Use the version
ssocket= new ServerSocket(SERVER_PORT,BACKLOG,LOCAL_INET_ADDRESS);
and bind server to some constant local IP. Now use the port forwarding in the modem, to forward all requests to that local ip. Make sure that the firewall is not preventing you to use the port. Since firewall may allow a local networking but not to web.
Client has sendpoints() method which is called by some other class that I did not include.
Anyways, sendpoints() is called and sends integers to the server, which receives them and send back to all the clients that are connected to the server(broadcast).
The problem is, clients keep sending integers while server is stuck in the thread I created for receiving integers(I think the server is not reading from inputstream).
I tried changing the stream, I tried putting integers together in a object and send it with ObjectOutputStream but none of these seems to work.
I need help (pointStruct is a class that holds some integer values I created)
import java.net.*;
import java.util.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class Server {
private ArrayList dataclient;
private ArrayList messageclient;
private ServerSocket dataserver;
private ServerSocket messageserver;
public static void main(String[] args) {
Server s1 = new Server();
s1.start();
}
// Start running server
public void start() {
try {
dataserver = new ServerSocket(4999);
messageserver = new ServerSocket(5000);
Socket dataconn;
Socket messageconn;
dataclient = new ArrayList();
messageclient = new ArrayList();
dataconn= null;
messageconn= null;
System.out.println("[server]start");
//start accepting connections
while (true) {
try {
dataconn = dataserver.accept();
System.out.println("[server]accepted dataconn");
messageconn = messageserver.accept();
System.out.println("[server]accepted messageconn");
//add clients to arraylist
dataclient.add(dataconn.getOutputStream());
messageclient.add(messageconn.getOutputStream());
}
catch (Exception ex) {
ex.printStackTrace();
}
//creating receiver threads
Thread t1 = new Thread(new DataReceiver(dataconn));
Thread t2 = new Thread(new MessageReceiver(messageconn));
System.out.println("[server]Thread successfully created");
t1.start();
t2.start();
System.out.println("[server]Thread successfully started");
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
//receive data from clients
public class DataReceiver implements Runnable {
BufferedReader br;
InputStream is;
int x,y;
int x2,y2;
int t;
int red;
int green;
int blue;
int size;
int dummy;
DataReceiver(Socket s){
try {
is=s.getInputStream();
//br = new BufferedReader(isr);
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public void run() {
while(true) {
try{
Iterator it = dataclient.iterator();
dummy=is.read();
if(dummy==9999) {
System.out.println("[server]executing data thread");
x=is.read();
System.out.println("[server]read a line"+x);
y=is.read();
System.out.println("[server]read a line"+y);
//x2=isr.read();
//y2=isr.read();
t=is.read();
red=is.read();
green=is.read();
blue=is.read();
size=is.read();
dummy=0;
//broadcast data
while (it.hasNext()) {
OutputStream os = (OutputStream)it.next();
os.write(9999);
os.write(x);
os.write(y);
os.write(t);
os.write(255);
os.write(0);
os.write(0);
os.write(size);
}
System.out.println("[server]data broadcasted");
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
//------------------------receive message from clients------------------------
public class MessageReceiver implements Runnable {
MessageReceiver(Socket s) {
}
public void run() {
}
}
}
public class networkHandler{
PrintWriter writer;
BufferedReader reader;
PrintWriter pwriter;
BufferedReader preader;
Socket sock;
Socket pointsock;
InputStream is;
JTextArea incoming;
pointHandler ph;
public networkHandler(pointHandler _ph) {
init();
ph=_ph;
setUpNetworking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
Thread pointerThread = new Thread(new ReceivingPoints());
pointerThread.start();
}
public void init() {
incoming = new JTextArea(20,20);
}
private void setUpNetworking() {
try {
// setup message port
System.out.println("networking establish started");
sock = new Socket("127.0.0.1",5000);
System.out.println("[NH]port 5000 established");
// setup point port
pointsock = new Socket("127.0.0.1",4999);
System.out.println("[NH]port 4999 established");
//message i/o stream
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
//point i/o stream
InputStreamReader pstreamReader = new InputStreamReader(pointsock.getInputStream());
System.out.println("networking establishing: Stream");
preader= new BufferedReader(pstreamReader);
pwriter= new PrintWriter(pointsock.getOutputStream());
System.out.println("networking establishing: Stream");
}
catch(IOException ex) {
ex.printStackTrace();
}
System.out.println("networking established");
}
//send message to the server
public void writeStream(String input){
try {
writer.println(input);
writer.flush();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public JTextArea getServerMessage() {
return incoming;
}
//receiving message from server
public class IncomingReader implements Runnable {
#Override
public void run() {
String message;
try {
while ((message = reader.readLine())!=null){
System.out.println("[NH] read from server:"+message);
incoming.append(message+"\n");
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
//receiving points from server
public class ReceivingPoints implements Runnable {
int x,y;
int x2,y2;
int red;
int green;
int blue;
int t;
int size;
int dummy;
pointStruct ps;
Color cr;
Point p;
synchronized public void run() {
try {
is = pointsock.getInputStream();
p= new Point();
}
catch(Exception ex) {
ex.printStackTrace();
}
while(true) {
try {
dummy=is.read();
if(dummy==9999) {
x=is.read();
y=is.read();
//x2=preader.read();
//y2=preader.read();
t=is.read();
red=is.read();
green=is.read();
blue =is.read();
size=is.read();
//create dummy pointStruct
ps = new pointStruct();
cr = new Color(red,green,blue);
p.x=x;
p.y=y;
ps.setP1(p);
p.x=x2;
p.y=y2;
//ps.setP2(p);
ps.setT((char)t);
ps.setS(size);
ps.setC(cr);
ph.save(ps);
dummy=0;
}
}
catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("[NH]receiving done");
}
}}
public void sendPoints(pointStruct ps) {
OutputStream os;
try{
os=pointsock.getOutputStream();
os.write(9999);
os.write(ps.getP1().x);
os.write(ps.getP1().y);
//pwriter.print(ps.getP2().x);
//pwriter.print(ps.getP2().y);
os.write(ps.getT());
os.write(ps.getC().getRed());
os.write(ps.getC().getGreen());
os.write(ps.getC().getBlue());
os.write(ps.getS());
}
catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("[NH]points sent to server");
}
}
You are reading the stream incorrectly, InputStream.read() returns a byte from the stream, but cast to an int.
InputStream.read() returns values from 0 to 255 is read is successful, and -1 if no more reading can be done (end of stream).
For example, InputStream.read() != 9999 always. So this ReceivingPoints.run() block will not fire:
while (true) {
try {
dummy = is.read();
if (dummy == 9999) {}
} catch(Exception ex) {
ex.printStackTrace();
}
}
You are looking for DataInputStream, it has methods for reading and writing other basic types than just bytes.