我目前在下面的類工作,while循環從客戶端發送包服務器畫圖程序:運行一個循環,每次一個點添加到一個ArrayList(Java)的
public class TCPClient extends JPanel {
public static ArrayList<Point> location = new ArrayList<>();
private JTextArea consoleOutput = new JTextArea(1,20);
public void addComponentToPane(Container pane) {
consoleOutput.setEditable(false);
}
public TCPClient() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
location.add(e.getPoint());
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
location.add(e.getPoint());
repaint();
}
});
setPreferredSize(new Dimension(800, 500));
setBackground(Color.WHITE);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(location.isEmpty()){
return;
}
Point p = location.get(0);
for (int i = 1; i < location.size(); i++) {
Point q = location.get(i);
g.drawLine(p.x, p.y, q.x, q.y);
p = q;
}
}
public static void main(String argv[]) throws Exception {
InetAddress SERVERIP = InetAddress.getLocalHost();
JFrame frame = new JFrame("Drawing with friends");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TCPClient(), BorderLayout.CENTER);
JTextArea IPadress = new JTextArea(1,20);
IPadress.setEditable(false);
IPadress.append("DEVICE IP: " + SERVERIP.getHostAddress());
frame.add(IPadress, BorderLayout.SOUTH);
frame.setSize(new Dimension(800,600));
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
while(true) {
try {
//BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 9000);
ObjectOutputStream outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
//ObjectInputStream inFromServer = new ObjectInputStream(clientSocket.getInputStream());
outToServer.writeObject(location);
outToServer.flush();
clientSocket.close();
Thread.sleep(100);
} catch (SocketException e) {
System.err.println(e.toString());
}
}
}
}
正如我while循環每個循環都會持續運行睡眠(100)。這按預期工作,但爲了提高效率,我希望每次在我的ArrayList位置中更改某個循環時都會運行循環,因此它不會發送不相關的軟件包。
我想要實現:
if(change in location) {
Send information to server
}
你試過了什麼?爲什麼它不起作用? – BeyelerStudios
將這些值添加到阻塞隊列中,允許「套接字」線程從此隊列中讀取並在每個點可用時發送它們。這樣做允許客戶端添加更多點,然後「套接字」線程可以發送,但允許「套接字」線程繼續處理隊列,直到它爲空,此時它將阻塞,等待下一批「點」 。這是「生產者 - 消費者」模式的一個例子 – MadProgrammer
對於它的價值,我會避免對象序列化,至少我不會序列化「整個」列表 – MadProgrammer