【发布时间】:2013-12-15 07:10:04
【问题描述】:
我在编程时遇到了相当烦人的问题。我是 Java 套接字的新手,并尽我所能学习,所以我提前道歉。无论如何,根据我当前程序的设置方式,我有一个在屏幕上移动的立方体,当你按下 Q 键时,它会将立方体的 x 和 y 坐标发送到服务器。第一次发送坐标时,它就像一个魅力;但是,第二次点击 Q 时,您会收到一条可爱的错误消息:"java.io.StreamCorruptedException: invalid stream header: 71007E00"。
这是我的代码:
SnakeServer 类
public class SnakeServer {
public static JFrame frame = new JFrame();
public static ArrayList<Integer> alist = new ArrayList<Integer>();
public static void main(String[] args) {
runServer();
}
public static void runServer() {
try {
Connection connection = new Connection();
connection.start();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
连接类
public class Connection extends Thread {
private volatile BufferedReader br;
private volatile PrintWriter pw;
private volatile ObjectInputStream oos;
private Socket s;
private ServerSocket ss;
Connection() throws IOException
{
ss = new ServerSocket(12355);
s = ss.accept();
//s.setKeepAlive(true);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
}
public void run()
{
try
{
while(true) {
System.out.print("Server has connected!\n");
oos = new ObjectInputStream(s.getInputStream());
Object obj = oos.readObject();
alist = (ArrayList<Integer>) obj;
System.out.println(alist.get(1));
System.out.println(alist.get(0));
}
}
catch(IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
SnakeGame 类
public class SnakeGame extends JPanel implements ActionListener {
public static Timer timer;
public static int x = 100;
public static int y = 100;
public static boolean left,right,up,down;
public static Socket skt;
public static DataInputStream in;
public static ObjectOutputStream out;
public static ArrayList<Integer> set = new ArrayList<Integer>();
public SnakeGame() {
timer = new Timer(100, this);
timer.start();
right = true;
setupConnection();
}
public void setupConnection() {
try {
skt = new Socket("localhost", 12355);
out = new ObjectOutputStream(skt.getOutputStream());
in = new DataInputStream(skt.getInputStream());
}
catch(IOException e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e) {
repaint();
move();
//connect();
}
public void move() {
if(right) {
x += 25;
}
if(left) {
x -= 25;
}
if(up) {
y -= 25;
}
if(down) {
y += 25;
}
if(x > 400) {
x = 0;
}
if(x < 0) {
x = 400;
}
if(y > 400) {
y = 0;
}
if(y < 0) {
y = 400;
}
}
public void paint(Graphics g) {
super.paint(g);
g.fillRect(x, y, 25, 25);
}
public static void connect() {
set.add(0, x);
set.add(1, y);
try {
//skt.setKeepAlive(true);
out.writeObject(set);
out.flush();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
【问题讨论】: