I'd like to make a program that can send signal through a network using DataInputStream but I have a trouble with the algorithm.
The program is simple actually. All I need is making two GUIs. The one is a color button (red, yellow, and blue button), another one is only three shapes that changes the color when we click the button.
So here is the client (signal buttons) code
connect.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
String str = tf.getText();
s = new Socket(str,54321);
out = s.getOutputStream();
dos = new DataOutputStream(out);
System.out.println("connection succeeded");
}catch(Exception ex){
System.out.println("connection error");
}
}
});
JButton disconnect = new JButton ("切断");
disconnect.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
dos.close();
out.close();
s.close();
System.out.println("connection closed");
}catch(Exception ex){
System.err.println("error -" +ex.toString());
}
}
});
And here is the server (signal lamps). This is the problem. Sorry if my code is not so efficient.
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.net.*;
import java.io.*;
public class lamp extends JFrame{
ServerSocket ss = null;
Socket s = null;
InputStream in = null;
DataInputStream dis = null;
String iro;
int s1,s2,s3;
private Container contentPane;
public lamp(String title){
super(title);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setSize(670,300);
setResizable(false);
setVisible(true);
}
public void paint(Graphics g){
g.setColor(Color.blue);
g.drawOval(10,50,200,200);
g.setColor(Color.yellow);
g.drawOval(220,50,200,200);
g.setColor(Color.red);
g.drawOval(430,50,200,200);
try{
ss = new ServerSocket(54321);
s = ss.accept();
in = s.getInputStream();
dis = new DataInputStream(in);
iro = dis.readUTF();
s1 = 0;
s2 = 0;
s3 = 0;
if(iro=="1"){
if(s1==0){
s1=1;
g.setColor(Color.blue);
g.fillOval(10,50,200,200);
System.out.println("received blue");
}else{
s1=0;
g.setColor(Color.blue);
g.fillOval(10,50,200,200);
System.out.println("received blue");
}
}
//its the same statement for yellow and red
}catch(Exception e){
System.out.println("error");
}
}
public static void main(String []args){
new lamp("lamp");
}
}
The result
error
error
error
error
error
Any idea?