java套接字编程问题(发送和接收数据)

时间:2011-02-18 04:21:08

标签: java sockets client

客户端有sendpoints()方法,该方法由我未包含的其他类调用。 无论如何,调用sendpoints()并将整数发送到服务器,服务器接收它们并发送回连接到服务器的所有客户端(广播)。

问题是,当服务器卡在我为接收整数而创建的线程中时,客户端继续发送整数(我认为服务器不是从输入流读取)。

我尝试更改流,我尝试将整数放在一个对象中并使用ObjectOutputStream发送它,但这些似乎都不起作用。 我需要帮助(pointStruct是一个包含我创建的整数值的类)

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");
    }       
}

1 个答案:

答案 0 :(得分:3)

您正在错误地读取流,InputStream.read()从流中返回一个字节,但转换为int。

InputStream.read()返回从0255的值,如果读取成功,则-1,如果不能再读取(流末尾)。

例如,InputStream.read() != 9999总是如此。所以这个ReceivingPoints.run()块不会触发:

while (true) {
    try {
        dummy = is.read();
        if (dummy == 9999) {}
    } catch(Exception ex) {
        ex.printStackTrace();
    }
}

您正在寻找DataInputStream,它有读取和写入其他基本类型的方法,而不仅仅是字节。