I'm working on a server-client game in which I need to update client's JFrame from the server in a specific period.this is my game
The problem is that the client's JFrame does not update.to be sure,I have rendered the JFrame Submitted by the server and it's OK,but the client's JFrame does not change at all.Here's my code:
my server:
public class main implements java.io.Serializable{
static ArrayList<Socket> allsockets = new ArrayList<>();
static ArrayList<ObjectOutputStream> oos = new ArrayList<>();
static final MainFrame frame=new MainFrame();
static boolean testfirst=false;
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
// TODO Auto-generated method stub
String name;
String color;
Color color1 = null;
Socket clientsocket=null;
ServerSocket serversocket=null;
PrintStream os = null;
ObjectInputStream is=null;
try{
serversocket = new ServerSocket(); // don't bind just yet
serversocket.setReuseAddress(true);
serversocket.bind(new InetSocketAddress(5555)); // can bind with reuse= true
}
catch(IOException e){
System.out.println(e);
}
while(true){
try {
clientsocket=serversocket.accept();
allsockets.add(clientsocket);
oos.add(new ObjectOutputStream(clientsocket.getOutputStream()));
is=new ObjectInputStream(clientsocket.getInputStream());
os = new PrintStream(clientsocket.getOutputStream());
try {
name =(String) is.readObject();
color=(String) is.readObject();
try {
java.lang.reflect.Field field = Class.forName("java.awt.Color").getField(color);
color1 = (Color)field.get(null);
} catch (Exception e) {
color = null;
}
player p=new player();
frame.addplayer(name, color1,p);
if(!testfirst){
testfirst=true;
new Thread(){
public void run(){
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("timer works");
for(ObjectOutputStream os:oos){
try {
os.writeObject(frame);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 1, 1);
}
}.start();
}
handle h= new handle(is, frame, p);
h.start();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
my client:
public class client implements java.io.Serializable {
static private final Lock mutex = new ReentrantLock(true);
private static final long serialVersionUID = 1L;
static double prevx =0;
static double prevy=0;
static Timer timer=new Timer();
static ObjectOutputStream os =null;
public static void main(String[]args) {
MainFrame frame=new MainFrame();
Socket clientSocket=null;
ObjectInputStream is=null;
String name;
String color;
try {
clientSocket = new Socket("localhost", 5555);
os = new ObjectOutputStream(clientSocket.getOutputStream());
is=new ObjectInputStream(clientSocket.getInputStream());
System.out.println("enter your name:");
Scanner in1=new Scanner(System.in);
name=in1.nextLine();
System.out.println("enter your color:");
color=in1.nextLine();
in1.close();
os.writeObject(name);
os.writeObject(color);
refresh ref=new refresh( is, os);
ref.start();
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to host");
}
}}
the refresh class(which has the responsibility to update client's JFrame)
public class refresh extends Thread{
MainFrame frame;
ObjectInputStream ois;
ObjectOutputStream oos;
Timer timer=new Timer();
double prevx,prevy;
private Lock mutex = new ReentrantLock(true);
public refresh(ObjectInputStream ois,ObjectOutputStream oos){
frame=new MainFrame();
this.ois=ois;
this.oos=oos;
}
public void run(){
while(true){
try {
frame= (MainFrame) ois.readObject();
frame.repaint();
frame.removeMouseMotionListener(mml);
frame.addMouseMotionListener(mml);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setFocusable(true);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MouseMotionListener mml=new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
mutex.lock();
try {
System.out.println("mouse moved");
oos.writeObject(arg0.getX());
oos.writeObject(arg0.getY());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mutex.unlock();
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
};}
and if needed the handle class(which receives the mouse coordinates from the client)
public class handle extends Thread{
double prevx,prevy;
MainFrame frame;
player myplayer;
ObjectInputStream ois;
double screenwidth,screenheigth;
boolean first=false;
boolean finished = false;
static private final Lock mutex = new ReentrantLock(true);
Thread movethread = new Thread(){
public void run(){
System.out.println("movethread run");
try {
if(Math.abs(prevx-myplayer.xcenter)>1 || Math.abs(prevy - myplayer.ycenter)>1){
while(Math.abs(prevx-myplayer.xcenter)!=0
|| Math.abs(prevy - myplayer.ycenter)!=0){
if(prevx<0 || prevx>screenwidth || prevy<0 || prevy>screenheigth)break;
myplayer.movem(prevx, prevy,mutex);
frame.repaint();
System.out.println(myplayer.cp.getCenter());
}
finished = true;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
public handle(ObjectInputStream ois,MainFrame frame,player p) {
// TODO Auto-generated constructor stub
this.myplayer=p;
this.ois=ois;
this.frame=frame;
this.screenwidth=frame.getscreenwidth();
this.screenheigth=frame.getscreenheigth();
}
public void run(){
System.out.println("handle thread run");
while(true){
try {
System.out.println("in handle");
System.out.println(first);
prevx= (double) ois.readObject();
prevy=(double) ois.readObject();
if(!first){
System.out.println("movethread started");
movethread.start();
first = true;
}
else if(first && finished){
movethread.run();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void update(double x,double y){
this.prevx=x;
this.prevy=y;
}}
Any help would be appreciated.
Related
i am currently working on a chat server as a project an need a bit of help. i have a multithreaded chat server where i want the clients to be able to close their chat window without crashing the server because it loses connection. So far so good. i have a working gui, and when i have a single client logged in to the server it works just fine to close the window and so closing the clientIOProcessor without the server crashing.
However, when i have multiple clients logged in to the server and want to close one of them the hole thing crashes
here is the ClientIOProcessor:
public class ClientIOProcessor extends Object implements Runnable, InputListener {
private ObjectInput socketInput;
private ObjectOutput socketOutput;
private boolean keepRunning;
private ClientModelDistributor assignedModelDistributor;
private MessageImplementation currentMessage;
private UserHub userHub;
public ClientIOProcessor(ClientModelDistributor _assignedModelDistributor, ObjectInput _socketInput,
ObjectOutput _socketOutput) {
this.assignedModelDistributor = _assignedModelDistributor;
this.socketInput = _socketInput;
this.socketOutput = _socketOutput;
assignedModelDistributor.getInputHandler().registerInputListener(this);
keepRunning = true;
}
public ClientIOProcessor(ClientLoginProcessor clientLoginProcessor, UserHub userHub) {
assignedModelDistributor = clientLoginProcessor.assignedModelDistributor;
socketInput = clientLoginProcessor.socketInput;
socketOutput = clientLoginProcessor.socketOutput;
assignedModelDistributor.getInputHandler().registerInputListener(this);
assignedModelDistributor.getIncomingMessageHandler().addIncomingMessageListener(userHub);
keepRunning = true;
this.userHub = userHub;
}
public void run() {
while (keepRunning) {
currentMessage = null;
currentMessage = buildMessageFromInput();
if(currentMessage == null) return;
switch (currentMessage.getMessageType()) {
case CHATMSG:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case USRJOINED:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case USRLEFT:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case TERMINATE:
this.terminateConnection();
break;
default:
System.out.println("An error occurred.");
}
}
}
public void terminateConnection() {
keepRunning = false;
assignedModelDistributor.getIncomingMessageHandler().removeIncomingMessageListener(this.userHub);
assignedModelDistributor.getInputHandler().removeInputListener(this);
try {
socketInput.close();
socketOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
// System.exit(0);
}
private MessageImplementation buildMessageFromInput() {
MessageImplementation messageSentByServer = null;
try {
messageSentByServer = (MessageImplementation) socketInput.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return messageSentByServer;
}
/**
* This method can be used to send <code>messages</code> to the server.
*
* #param message
* #throws IOException
*/
public void send(Message message) throws IOException {
try {
socketOutput.writeObject(message);
socketOutput.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This method is called whenever the user enters input to this
* <code>InputListener</code>'s corresponding <code>InputHandler</code>.
*/
#Override
public void inputEntered(String input) {
try {
send(assignedModelDistributor.buildUserMessage(input));
} catch (IOException e) {
e.printStackTrace();
}
}
}
the clientIO processor gets the TERMINATE message from the server and calls the terminateConnection() Method to end the Streams.
Here is the ServerIOProcessor:
public class ServerIOProcessor implements Runnable, IncomingMessageListener {
private ServerModelDistributor assignedModelDistributor;
private User assignedUser;
private boolean keepRunning;
private ObjectInputStream socketInput;
private ObjectOutputStream socketOutput;
private MessageImplementation currentMessage;
private final String SYSTEM = "System";
public ServerIOProcessor(User _assignedUser, ObjectOutputStream _socketOutput, ObjectInputStream _socketInput,
ServerModelDistributor _assignedModelDistributor) {
assignedUser = _assignedUser;
socketInput = _socketInput;
socketOutput = _socketOutput;
assignedModelDistributor = _assignedModelDistributor;
keepRunning = true;
assignedModelDistributor.getIncomingMessageHandler().addIncomingMessageListener(this);
}
public void run() {
while (keepRunning) {
currentMessage = null;
currentMessage = buildMessageFromInput();
switch (currentMessage.getMessageType()) {
case CHATMSG:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
break;
case NEWTASK:
createNewTask();
break;
case TASKASSGNMNT:
assignTaskToUser();
break;
case NEWLEADER:
determineLeaderOfTeam();
break;
case ADDTEAM:
addTeam();
break;
case RMVTEAM:
removeTeam();
break;
case ADDTEAMMEMBER:
addUserToTeam();
break;
case RMVTEAMMEMBER:
removeUserFromTeam();
break;
case JOINTEAM:
joinTeam();
break;
case LEAVETEAM:
leaveTeam();
break;
case EDITDETAILS:
editUserDetails();
break;
case TERMINATE:
assignedModelDistributor.getIncomingMessageHandler().enterMessage(currentMessage);
letClientLeaveServer();
break;
default:
send(newSystemMessage(MessageType.ERROR));
System.out.println("An error occured in one of the server's active IO processes.");
break;
}
}
}
private void createNewTask() {
}
private void assignTaskToUser() {
// TODO Auto-generated method stub
}
private void determineLeaderOfTeam() {
// TODO Auto-generated method stub
}
private void addTeam() {
// TODO Auto-generated method stub
}
private void removeTeam() {
// TODO Auto-generated method stub
}
private void addUserToTeam() {
// TODO Auto-generated method stub
}
private void removeUserFromTeam() {
// TODO Auto-generated method stub
}
private void joinTeam() {
// TODO Auto-generated method stub
}
private void leaveTeam() {
// TODO Auto-generated method stub
}
private void editUserDetails() {
// TODO Auto-generated method stub
}
private void letClientLeaveServer() {
// TODO Auto-generated method stub
assignedModelDistributor.getIncomingMessageHandler().removeIncomingMessageListener(this);
try {
socketInput.close();
socketOutput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
keepRunning = false;
}
private MessageImplementation buildMessageFromInput() {
MessageImplementation messageSentByUser = null;
try {
messageSentByUser = (MessageImplementation) socketInput.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return messageSentByUser;
}
private MessageImplementation newSystemMessage(MessageType msgtype) {
return new MessageImplementation(SYSTEM, msgtype);
}
//TODO Check expected purpose of this method.
/**
* This method is called whenever a <code>Message</code> is entered to the
* corresponding <code>IncomingMessageHandler</code>.
*/
#Override
public void messageEntered(Message message) {
// assignedModelDistributor.getIncomingMessageHandler().enterMessage(message);
try {
socketOutput.writeObject(message);
socketOutput.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Writes the given <code>Message</code> to the Socket's
* <code>ObjectInputStream</code>.
*
* #throws IOException
*/
void send(Message message) {
try {
socketOutput.writeObject(message);
socketOutput.flush();
} catch (Exception r) {
System.out.println("Error!");
r.printStackTrace();
}
}
}
the important part here is the letClientLeaveServer() method to end the streams here as well. however, i think this is the wrong way, because i think this ends the Input/Ouput Streams for all logged in Clients.
The ServerSocket it self is initialized in another class ConnectionProcessor which starts the Socket on a given port and accepts it. then the connectionProcessor starts the serverLogInProcessor which starts a new Thread for the serverIOProcessor.
Here the ConnectionProcessor:
public class ConnectionProcessor implements Runnable {
private ServerModelDistributor assignedModelDistributor;
private boolean keepRunning;
private ServerSocket serverSocket;
private int assignedPort;
public ConnectionProcessor(int _assignedPort, ServerModelDistributor _assignedModelDistributor) {
assignedModelDistributor = _assignedModelDistributor;
assignedPort = _assignedPort;
keepRunning = true;
try {
serverSocket = new ServerSocket(assignedPort);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (keepRunning) {
if(serverSocket.isClosed()) {
try {
serverSocket = new ServerSocket(assignedPort);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Socket socketCreatedForLoginProcess = serverSocket.accept();
serverSocket.close();
Thread serverLoginProcessor = new Thread(
new ServerLoginProcessor(this, socketCreatedForLoginProcess, assignedModelDistributor),
"loginProcess");
serverLoginProcessor.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I want to send object (custom class) via socket from Client to Server. This is my code:
Server:
private class SocketServerThread extends Thread {
#Override
public void run() {
try {
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
clientSocket = serverSocket.accept();
ObjectInputStream inObject = new ObjectInputStream(
clientSocket.getInputStream());
try {
Te xxx = (Te) inObject.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//DataInputStream dataInputStream = new DataInputStream(
//clientSocket.getInputStream());
//messageFromClient=dataInputStream.readUTF();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//activity.msgFromC.setText(messageFromClient);
}
});
}
}
Client:
public Client(String aIPaddres, int aPort, Te u) {
AddressIP = aIPaddres;
Port = aPort;
sendUser = u;
}
protected Void doInBackground(Void... arg0) {
Socket clientSocket = null;
try {
clientSocket = new Socket(AddressIP, Port);
ObjectOutputStream outObject = new ObjectOutputStream(
clientSocket.getOutputStream());
outObject.writeObject(sendUser);
//DataOutputStream daneWyjsciowe = new DataOutputStream(
//clientSocket.getOutputStream());
//daneWyjsciowe.writeUTF("Czesc!" );
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "IOException: " + e.toString();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
Custom class (Te.class):
public class Te implements Serializable {
public String message;
public Te(String m){
message=m;
}
}
When I passing simple data i.e. String there is no problem. But now I want to pass object, but there is always ClassNotFoundException at server. I read lot of stacks but I didnt find answer. Could U help me?
I have two buttons and and Timer. When I run the code it gets connected to the Socket. For every 1000 milliseconds timer should send the command(message) to the Socket and simultaneously when I click a button it should send other message as in the code. But problem is that when I click a button either the messages which are sent are delayed or messages are not sent properly through dat is the receiving end is not receiving properly.
How to handle this issue?
Here is my code
public static void main(String[] args)
{
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
configure config=new configure();
config.run();
config.setVisible(true);
}
});
}
protected void run()
{
// TODO Auto-generated method stub
try {
connection.setText("Connected to < NONE >");
socket=new Socket("192.168.1.3",3000);
// System.out.println("Connection Established") ;
connection.setText("CONNECTION ESTABLISHED WITH : " + "< " +
socket.getInetAddress() + " >" + "\n");
} catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// System.out.println("connection failed");
connection.setText("CONNECTION FAILED");
}
}
public configure()
{
setResizable(false);
setBounds(300,80,800,600);
contentPane=new JPanel();
contentPane.setBorder(new EmptyBorder(5,5,5,5));
setContentPane(contentPane);
contentPane.setLayout(null);
configlabel=new JLabel("CONFIGURE YOUR MODEL");
configlabel.setBounds(210,20,500,40);
configlabel.setFont(new Font("arial",Font.BOLD,28));
contentPane.add(configlabel);
connection=new JLabel();
connection.setBounds(12,80,500,40);
connection.setFont(new Font("arial",Font.BOLD,16));
contentPane.add(connection);
channel1=new JLabel("Channel 1");
channel1.setBounds(80, 140, 80, 30);
channel1.setFont(new Font("arial",Font.BOLD,15));
contentPane.add(channel1);
channel1Field=new JTextField();
channel1Field.setBounds(55, 200, 120, 30);
channel1Field.setEnabled(true);
contentPane.add(channel1Field);
channel1send=new JButton("Send 1");
channel1send.setBounds(65, 270, 100, 30);
channel1send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
if(!(channel1Field.getText().equals("")))
{
// TODO Auto-generated method stub
if(channel1send.isEnabled())
{
new Thread(new Channel1()).start();
}
}
else
{
JOptionPane optionPane = new JOptionPane("Field cannot be
empty", JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog("FAILURE");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
}
});
contentPane.add(channel1send);
channel2=new JLabel("Channel 2");
channel2.setBounds(255, 140, 80, 30);
channel2.setFont(new Font("arial",Font.BOLD,15));
contentPane.add(channel2);
channel2Field=new JTextField();
channel2Field.setBounds(230, 200, 120, 30);
channel2Field.setEnabled(true);
contentPane.add(channel2Field);
channel2send=new JButton("Send 2");
channel2send.setBounds(250, 270, 80, 30);
channel2send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(!(channel2Field.getText().equals("")))
{
if(channel2send.isEnabled())
{
new Thread(new Channel2()).start();
}
}
else
{
JOptionPane optionPane = new JOptionPane("Field cannot
be empty", JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog("FAILURE");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
}
});
contentPane.add(channel2send);
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 1000);
}
class SayHello extends TimerTask {
public void run() {
try
{
byte[] com=new byte[]{0x01,(byte)0xFE};
socket=new Socket("192.168.1.3",3000);
DataOutputStream dw=new DataOutputStream(socket.getOutputStream());
dw.writeInt(com.length);
dw.write(com);
StringBuilder sb=new StringBuilder();
for(byte b:com)
{
sb.append(String.format("%02X ", b));
}
sentmessage.append("Timer Sent - " + sb.toString() + "\n");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
class Channel1 implements Runnable
{
#Override
public void run()
{
// TODO Auto-generated method stub
try {
String message1=channel1Field.getText();
int msg1=Integer.parseInt(message1);
command=new byte[]{(byte)0xFE,0x01,0x01,(byte)msg1,0x00,0x00,(byte)0xFD};
DataOutputStream dw=new DataOutputStream(socket.getOutputStream());
// dw.writeInt(command.length);
dw.write(command);
StringBuilder sb=new StringBuilder();
// System.out.println(Arrays.toString(command));
for(byte b:command)
{
sb.append(String.format("%02X ", b));
}
sentmessage.append("Client Sent to Channel 1 - " +
sb.toString() + "\n");
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
sentmessage.append("channel 1 failed to send");
}
finally
{
if(socket!=null)
{
try
{
socket.close();
socket=new Socket("192.168.1.3",3000);
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
class Channel2 implements Runnable
{
#Override
public void run()
{
// TODO Auto-generated method stub
try {
String message2=channel2Field.getText();
int msg2=Integer.parseInt(message2);
command=new byte[]{(byte)0xFE,0x01,0x02,(byte)msg2,0x00,0x00(byte)0xFD};
DataOutputStream dw=new DataOutputStream(socket.getOutputStream());
// dw.writeInt(command.length);
dw.write(command);
StringBuilder sb=new StringBuilder();
for(byte b:command)
{
sb.append(String.format("%02X ", b));
}
sentmessage.append("Client Sent to Channel 2 - " +
sb.toString() + "\n");
}
catch (IOException e1)
{
e1.printStackTrace();
sentmessage.append("channel 2 on failed");
}
finally
{
if(socket!=null)
{
try {
socket.close();
socket=new Socket("192.168.1.3",3000);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
I have been trying to work this out by myself these past few days but I just can't seem to be able to get to a solution...... how do I force paint a JFrame and everything inside it? I have a Chat programme (client/server approach), the server class and the client one are identical code-wise? But I just can't seem to make the client one show!
import java.awt.event.ActionEvent;
public class Chat extends JFrame implements Runnable, ActionListener, WindowListener{
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField line;
// TCP Components
private Socket channel = null;
private JScrollPane scrollPane;
private String toBeSent="";
private final String END_CHAT_SESSION = new Character((char)0).toString();
private PrintWriter out;
private boolean channelIsStillOpen = true;
private Socket channel;
private static JTextArea chatText;
public Chat(Socket channel) {
this.channel=channel;
addWindowListener(this);
setTitle("Remote Administrator");
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
line = new JTextField();
line.setBounds(17, 207, 289, 40);
line.setColumns(10);
JButton send = new JButton("Send");
send.addActionListener(this);
send.setBounds(312, 214, 105, 25);
contentPane.setLayout(null);
scrollPane = new JScrollPane();
scrollPane.setBounds(17, 5, 399, 196);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
contentPane.add(scrollPane);
chatText = new JTextArea();
chatText.setLineWrap(true);
chatText.setEditable(false);
chatText.setEnabled(false);
scrollPane.setViewportView(chatText);
contentPane.add(line);
contentPane.add(send);
}
#Override
public void run() {
try {
channel=new Socket(address, port);
System.out.println("Chat Connection accepted");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out = null;
try {
out = new PrintWriter(channel.getOutputStream(),true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String s="";
do {
// Send data
if (toBeSent.length()!= 0) {
out.println(toBeSent);
toBeSent="";
}
// Receive data
try {
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0) && !s.equals(END_CHAT_SESSION)) {
chatText.append("INCOMING: " + s + "\n");
}
if(s.equals(END_CHAT_SESSION)){
chatText.append("Client disconnected.");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while(!s.equals(END_CHAT_SESSION));
channelIsStillOpen=false;
line.setEditable(false);
line.setEnabled(false);
if(channel!=null){
try {
channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
channel=null;
}
}
#Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosing(WindowEvent arg0) {
if(channelIsStillOpen){
out.println(END_CHAT_SESSION);
}
dispose();
}
#Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
String s = line.getText();
if (!s.equals("")) {
chatText.append("OUTGOING: " + s + "\n");
// Send the string
toBeSent=s;
}
line.setText("");
}
}
edit: I have even edited the code so that the class being used is always the same! Nothing!
I think you are missing this at the end of your constructor:
this.setVisible(true);
also, why don't you set? setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, why do you want to keep the application opened?
I need Your help!
So I got this app on an Android device, in which I get data from the accelerometer, and button presses which get this data to an edittext, and sets listeners on the edittextes.
When it's changed, there's a functions that creates a socket, sends data, and closes the socket.
Then I have a server app on my computer, in which I create serversockets, and create two threads that are waiting for serversocket.accept() that gets the data and put it into texbox. Simple as that.
I'm glad that I got it working anyway :-) but the point is, it's not working so well. I believe that whole communication is bad and not optimized. It sends data well, but often freezes, then unfreezes and sends quickly all previous data and so on.
I'm sorry for my bad code, but can someone please take a good look on this, and propose what I should change and how I could make it work more smooth and stable? :-(
Here's the Client code:
package com.test.klienttcp;
//import's...
public class Klient extends Activity implements SensorListener {
final String log = "Log";
EditText textOut;
EditText adres;
EditText test;
EditText gazuje;
TextView textIn;
TextView tekst;
TextView dziala;
String numer = null;
float wspk = 0; // wspolczynniki kalibracji
float wychylenietmp = 0;
float wychylenie = 0;
int tmp = 0;
int i = 0;
boolean wysylaj = false;
SensorManager sm = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
adres = (EditText)findViewById(R.id.adres);
gazuje = (EditText)findViewById(R.id.gazuje);
Button kalibracja = (Button)findViewById(R.id.kalibracja);
Button polacz = (Button)findViewById(R.id.polacz);
Button gaz = (Button)findViewById(R.id.gaz);
Button hamulec = (Button)findViewById(R.id.hamulec);
kalibracja.setOnClickListener(kalibracjaOnClickListener);
polacz.setOnClickListener(polaczOnClickListener);
gaz.setOnTouchListener(gazOnTouchListener);
hamulec.setOnTouchListener(hamulecOnTouchListener);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
//text listener steering
textOut.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(wysylaj)
{
Wyslij();
}
}
});
//text listener for throttle
gazuje.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(wysylaj)
{
Gaz();
}
}
});
}
Button.OnClickListener polaczOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(wysylaj==false)
{
wysylaj = true;
}
else
{
wysylaj = false;
}
}};
//throttle button handler
Button.OnTouchListener gazOnTouchListener
= new Button.OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN) {
gazuje.setText("1");
} else if (event.getAction() == MotionEvent.ACTION_UP) {
gazuje.setText("0");
}
return false;
}};
//brake button handler
Button.OnTouchListener hamulecOnTouchListener
= new Button.OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN) {
gazuje.setText("2");
} else if (event.getAction() == MotionEvent.ACTION_UP) {
gazuje.setText("0");
}
return false;
}};
//sensor handler
public void onSensorChanged(int sensor, float[] values) {
synchronized (this) {
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
wychylenie = values[0] * 10;
tmp = Math.round(wychylenie);
wychylenie = tmp / 10;
if(wychylenie != wychylenietmp)
{
textOut.setText(Float.toString(wychylenie - wspk));
wychylenietmp = wychylenie;
}
}
}
}
public void onAccuracyChanged(int sensor, int accuracy) {
Log.d(log, "onAccuracyChanged: " + sensor + ", accuracy: " + accuracy);
}
#Override
protected void onResume() {
super.onResume();
sm.registerListener(this, SensorManager.SENSOR_ORIENTATION
| SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
sm.unregisterListener(this);
super.onStop();
}
//callibration handler
Button.OnClickListener kalibracjaOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
wspk = wychylenie;
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
// sending steering data
public void Wyslij()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
numer = adres.getText().toString();
socket = new Socket(numer, 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
if(socket.isClosed())
{
test.setText("Socket zamkniety");
}
//textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//sending throttle data
public void Gaz()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
numer = adres.getText().toString();
socket = new Socket(numer, 8889);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(gazuje.getText().toString());
if(socket.isClosed())
{
test.setText("Socket zamkniety");
}
//textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
And here's Server code:
//import's...
public class Okno
{
public static float wychylenie;
public static String gaz="0";
public static float jedzie;
public static int skrecam, gazuje;
public static String wiadomosc="100";
private static int maxConnections=0, port=8888, portg=8889;
public static void main(String[] args)
{
skrecam = 0;
gazuje = 0;
Window ok = new Window();
ok.setDefaultCloseOperation(3);
ok.setVisible(true);
ok.setResizable(false);
ok.setTitle("Serwer TCP");
int i=0;
try{
Robot robot = new Robot();
Robot robotgaz = new Robot();
ServerSocket listener = new ServerSocket(port);
ServerSocket listenergaz = new ServerSocket(portg);
while((i++ < maxConnections) || (maxConnections == 0)){
//create thread for steering
if(skrecam == 0)
{
skrecam=1;
doComms conn_c= new doComms(listener);
Thread t = new Thread(conn_c);
t.start();
}
//create thread for throttle
if(gazuje == 0)
{
gazuje=1;
doCommsgaz conn_gaz= new doCommsgaz(listenergaz);
Thread tgaz = new Thread(conn_gaz);
tgaz.start();
}
ok.pole3.setText(wiadomosc);
ok.pole2.setText(gaz);
}
}
catch (AWTException e) {
e.printStackTrace();
}
catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doComms implements Runnable {
private Socket server;
private ServerSocket listener;
private String line,input;
doComms(ServerSocket listener) {
this.listener=listener;
}
public void run () {
input="";
try {
Socket server;
server = listener.accept();
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
//PrintStream out = new PrintStream(server.getOutputStream());
Okno.wiadomosc = in.readUTF();
server.close();
Okno.skrecam=0;
} catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doCommsgaz implements Runnable {
private Socket server;
private ServerSocket listener;
private String line,input;
doCommsgaz(ServerSocket listener) {
this.listener=listener;
}
public void run () {
input="";
try {
Socket server;
server = listener.accept();
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
//PrintStream out = new PrintStream(server.getOutputStream());
Okno.gaz = in.readUTF();
server.close();
Okno.gazuje=0;
} catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class Window extends JFrame {
private JButton ustaw;
public JTextField pole1;
public JTextField pole2;
public JTextField pole3;
Window()
{
setSize(300,200);
getContentPane().setLayout(new GridLayout(4,1));
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout(1));
getContentPane().add(panel1);
pole1 = new JTextField(15);
panel1.add(pole1);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(1));
getContentPane().add(panel2);
pole2 = new JTextField(15);
panel2.add(pole2);
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout(1));
getContentPane().add(panel3);
pole3 = new JTextField(15);
panel3.add(pole3);
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout(1));
getContentPane().add(panel4);
ustaw = new JButton("Ustaw");
panel4.add(ustaw);
//action button handler
ustaw.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent zdarz){
try{
}
catch(Exception wyjatek){}
pole1.setText("costam");
}
});
}
}
Once again, sorry for the non optimized, and hard-to-read code. But please, if someone knows what would be better, please respond.
Thanks a lot!
The client socket code should go into an AsyncTask. Google has a good into to it here. This will not speed anything up but it will stop your app from freezing. You can put in a "Processing" message while displaying a progress dialog to let the user know that something is happening.