2

ソケットでいくつかの問題が発生しています。

複数のクライアントを受け入れる同時サーバーを作成しようとしています。

クライアントがサーバーに接続すると、サーバーは新しいスレッドを作成し、ソケットをリッスンします。次に、クライアントが何かを送信した場合、サーバーはそれを読み取る必要があります。

クライアントでは、辞書 (txt 形式) を開き、それをソケット経由で送信します。

サーバー上で私が得る唯一のものはこれです:

#

ヌル

サーバ

    try
             {
                String message,file = new String("StressTextFile.txt");
                File filee = new File(file);
                long length;

                 // Open the file 
                 FileInputStream fstream = new FileInputStream(file);
                 // Get the object of DataInputStream
                 DataInputStream in = new DataInputStream(fstream);
                 BufferedReader br = new BufferedReader(new InputStreamReader(in));
                 String strLine = new String();

                 length  = filee.length();

                 ProgressBar.setMaximum((int)length); //we're going to get this many bytes
                 ProgressBar.setValue(0); //we've gotten 0 bytes so far
                  //Read File Line By Line

                font1 = new Font("Helvetica", Font.PLAIN, 18);
                font1.isBold();
                color = new Color( 74,118,110);
                TextArea1.setForeground(color);
                TextArea1.setFont(font1);

                 int soma=0;
                    while(in.readLine() != null)
                    {
                        strLine = in.readLine();  // reads from file
                        //System.out.println(strLine);


                        TextArea1.append(strLine+"\n");

                        pwOut.write(strLine);
                        pwOut.flush();

                        soma+=strLine.length()+1;
                        ProgressBar.setValue(ProgressBar.getValue()+(strLine.length()+1)*2);
                        ProgressBar.repaint();              
                    };

                    br.close();
                    pwOut.close();
                    Skt.close();
            }catch (Exception e){  System.err.println("Error: " + e.getMessage());  }
          }

クライアント

    try
    {

        brIn = new BufferedReader(new InputStreamReader(skt.getInputStream()));


        while(s != null)
        {

            s = brIn.readLine();
            System.out.println("#####");
            System.out.println(s);
        }

    } 
    catch (IOException e1) {e1.printStackTrace();    }

Swing コンポーネントは忘れてください。私はすべてのソケットのものは大丈夫だと思います。サーバー側で何も取得できないのはなぜですか?

助けてください

敬具

4

2 に答える 2

4

マルチスレッド サーバーのベアボーンの例:

//MyServer.java
public class MyServer {

  private static int PORT = 12345;

  public static void main(String args[]) {

    ServerSocket s = new ServerSocket(PORT);
    while(true) new MyServerThread(s.accept());

  }

そしてあなたのサーバースレッド:

//MyServerThread.java
public class MyServerThread implements Runnable {

  private InputStream in = null;
  private OutputStream out = null;

  public MyServerThread(Socket s) {

    in = s.getInputStream();
    out = s.getOutputStream();

    (new Thread(this)).start();
  }

  public void run() {
    //do stuff with **in** and **out** to interact with client
  }
}

この例にはありません:

  • エラー処理
  • close()ソケット/ストリームの ing
  • サーバーのシャットダウン
  • クライアントサイド

うまくいけば、それが通常どのように見えるかについてのアイデアをあなたに与えるでしょう.

于 2012-10-17T17:51:39.903 に答える
0

サーバーは次のようなものです。

public class KnockKnockServer { public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;
        RunnableThread rt;

        try { serverSocket = new ServerSocket(4443);} 
        catch (IOException e) 
        {
            System.err.println("Could not listen on port: 4443.");
            System.exit(1);
        }

        Socket clientSocket = null;
        try 
        { 

            clientSocket = serverSocket.accept();
            rt = new RunnableThread("t1",clientSocket);
        } 
        catch (IOException e)
        {
            System.err.println("Accept failed.");
            System.exit(1);
        }

        serverSocket.close();
    }
}


        class RunnableThread implements Runnable 
{

    Thread runner;
    Socket skt;

    public RunnableThread(String threadName,Socket cliSock) 
    {
        runner = new Thread(this, threadName); // (1) Create a new thread.


        skt = cliSock;
        runner.run();
    }
    @SuppressWarnings("deprecation")
    public void run() 
    {

        //Display info about this particular thread
        //System.out.println(Thread.currentThread());

        //PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
        BufferedReader brIn;
        String s = new String();


        try
        {

            brIn = new BufferedReader(new InputStreamReader(skt.getInputStream()));


            while(s != null)
            {

                s = brIn.readLine();
                System.out.println("#####");
                System.out.println(s);
            }

        } 
        catch (IOException e1) {e1.printStackTrace();    }

    }
}

クライアントでサーバーとやり取りするのは、辞書ファイル (StressTextFile.txt) から単語を読み取り、ソケット経由で送信するときだけです。

public void SendToServer()
    {

        new Thread() 
            {
              public void run() 
              {
                try
                 {
                    String message,file = new String("StressTextFile.txt");
                    File filee = new File(file);
                    long length;

                     // Open the file 
                     FileInputStream fstream = new FileInputStream(file);
                     // Get the object of DataInputStream
                     DataInputStream in = new DataInputStream(fstream);
                     BufferedReader br = new BufferedReader(new InputStreamReader(in));
                     String strLine = new String();

                     length  = filee.length();

                     ProgressBar.setMaximum((int)length); //we're going to get this many bytes
                     ProgressBar.setValue(0); //we've gotten 0 bytes so far
                      //Read File Line By Line

                    font1 = new Font("Helvetica", Font.PLAIN, 18);
                    font1.isBold();
                    color = new Color( 74,118,110);
                    TextArea1.setForeground(color);
                    TextArea1.setFont(font1);

                     int soma=0;
                        while(in.readLine() != null)
                        {
                            strLine = in.readLine();  // reads from file
                            //System.out.println(strLine);


                            TextArea1.append(strLine+"\n");

                            pwOut.write(strLine);
                            pwOut.flush();

                            soma+=strLine.length()+1;
                            ProgressBar.setValue(ProgressBar.getValue()+(strLine.length()+1)*2);
                            ProgressBar.repaint();              
                        };

                        br.close();
                        pwOut.close();
                        Skt.close();
                }catch (Exception e){  System.err.println("Error: " + e.getMessage());  }
              }
            }.start();
    } 

ドキュメントについて:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import javax.swing.*;
import javax.swing.border.Border;


public class Graphics extends JFrame  implements ActionListener 
{

    private JPanel Panel;
    public JLabel LabelConnect;
    public JLabel DataSent;
    public JLabel DataReceived;
    private JTextField TextFieldOutPUT;
    private JButton ConnectButton;
    private JButton Sendinformation;
    private int value;
    private JTextArea TextArea1; 
    private JTextArea TextArea2; 
    private JProgressBar ProgressBar;
    private Socket Skt;
    private PrintWriter pwOut;
    private boolean CONNECTED;
    private Border border;
    private Color color;
    private Font font1;
    private JScrollPane ScrollBar1;
    private JScrollPane ScrollBar2;

    public Graphics() throws UnknownHostException, IOException
    {


        value = 0;

        Panel = new JPanel();

        font1 = new Font("Helvetica", Font.PLAIN, 15);
        font1.isBold();

        LabelConnect = new JLabel();
        DataReceived = new JLabel();
        DataSent = new JLabel();
        TextFieldOutPUT = new JTextField();
        ConnectButton = new JButton("Connect");
        TextArea1 = new JTextArea("ola");
        TextArea2 = new JTextArea("Adeus");
        Sendinformation = new JButton("Send");
        ProgressBar = new JProgressBar();

        Sendinformation.setLayout(null);
        Sendinformation.setBounds(340, 450, 100, 25);
        Sendinformation.setVisible(true);
        Sendinformation.addActionListener(this);


        color = new Color( 211,211,211);

        TextArea1.setVisible(true);
        TextArea1.setLayout(null);
        TextArea2.setVisible(true);
        TextArea2.setLayout(null);

        ScrollBar1 = new JScrollPane(TextArea1);
        ScrollBar1.setLayout(null);
        ScrollBar1.setVisible(true);
        ScrollBar1.setBounds(210,40,15,400);
        ScrollBar1.setEnabled(true);
        ScrollBar1.setVisible(true);
        ScrollBar1.setBackground(color);
        ScrollBar1.setBounds(10,40,210,400);

        ScrollBar2 = new JScrollPane(TextArea2);
        ScrollBar2.setLayout(null);
        ScrollBar2.setVisible(true);
        ScrollBar2.setEnabled(true);
        ScrollBar2.setBackground(color);
        ScrollBar2.setBounds(230,40,210,400);
        ScrollBar2.setLayout(null);
        ScrollBar2.setVisible(true);




        border = BorderFactory.createTitledBorder("Reading...");


        ProgressBar.setLayout(null);
        ProgressBar.setBounds(10,450,320,25);
        ProgressBar.setValue(0);
        ProgressBar.setStringPainted(true);

        //ProgressBar.setBorderPainted(border);
        ProgressBar.setVisible(true);




        TextFieldOutPUT.setVisible(true);
        TextFieldOutPUT.setBounds(10,500,320,25);

        ConnectButton.addActionListener(this);
        ConnectButton.setLayout(null);
        ConnectButton.setVisible(true);
        ConnectButton.setBounds(340, 500, 100, 25);

        LabelConnect.setBounds(10,478,320,25);
        LabelConnect.setVisible(true);
        LabelConnect.setFont(font1);
        LabelConnect.setForeground(Color.WHITE);
        LabelConnect.setText("Connect");

        font1 = new Font("Helvetica", Font.PLAIN, 18);


        DataReceived.setBounds(235,10,200,25);
        DataReceived.setVisible(true);
        DataReceived.setFont(font1);
        DataReceived.setForeground(Color.WHITE);
        DataReceived.setText("Data Received");

        DataSent.setBounds(15,10,200,25);
        DataSent.setVisible(true);
        DataSent.setFont(font1);
        DataSent.setForeground(Color.WHITE);
        DataSent.setText("Data Sent");



        color = new Color(108,166,205);
        Panel.setBackground(color);


        Panel.add(ScrollBar1);
        Panel.add(ScrollBar2);
        Panel.add(DataSent);
        Panel.add(DataReceived);
        Panel.add(Sendinformation);
        Panel.add(ProgressBar);
        Panel.add(ConnectButton);
        Panel.add(TextFieldOutPUT);
        Panel.add(LabelConnect);
        Panel.setVisible(true);
        Panel.setLayout(null);
        Panel.setBounds(500,400,800,600);


        add(Panel);
        this.setSize(459,560 );

        setVisible(true);
    }



    @Override
    public void actionPerformed(ActionEvent e) 
    {

        //Object obj = new obj(e.get)

        if(e.getSource() == ConnectButton)
        {
            if(!CONNECTED)
            {
                String s = new String(TextFieldOutPUT.getText());

                try {Skt = new Socket(s, 4443); Skt.close();
                } catch (UnknownHostException e2) {e2.printStackTrace(); JOptionPane.showMessageDialog(Panel, "Connection could not be established!!"); return;
                } catch (IOException e2) {e2.printStackTrace(); JOptionPane.showMessageDialog(Panel, "Connection could not be established!!");return;}  



                System.out.println(s);

                try {ConnectCLIENT(s);
                } catch (UnknownHostException e1) {e1.printStackTrace();
                } catch (IOException e1) {e1.printStackTrace();}
            }
            else
            {
                try {   Skt.close();  } catch (IOException e1){  e1.printStackTrace();  }
                ConnectButton.setText("Connect");
                TextFieldOutPUT.setEditable(true);
                CONNECTED = false;
                Panel.repaint();

            }

        }

        if(e.getSource() == Sendinformation){ 

            System.out.print("Sendinformation");
            if(CONNECTED)
                SendToServer(); 
            else
                JOptionPane.showMessageDialog(Panel, "You are not connecte to the server!! Please connect!!");

        }

    }

    public void ConnectCLIENT(String socketStr) throws UnknownHostException, IOException
    {


        try{
            Skt = new Socket(socketStr, 4443);
            pwOut = new PrintWriter(Skt.getOutputStream(),true);
            System.out.print("Connected");
            TextFieldOutPUT.setEditable(false);
            ConnectButton.setText("Disconnect");
            CONNECTED = true;
            JOptionPane.showMessageDialog(Panel, "Connection Sucessfully established!!");
            Panel.repaint();
            }
        catch(Exception E){E.printStackTrace();}

    }

    public void SendToServer()
    {

        new Thread() 
            {
              public void run() 
              {
                try
                 {
                    String message,file = new String("StressTextFile.txt");
                    File filee = new File(file);
                    long length;

                     // Open the file 
                     FileInputStream fstream = new FileInputStream(file);
                     // Get the object of DataInputStream
                     DataInputStream in = new DataInputStream(fstream);
                     BufferedReader br = new BufferedReader(new InputStreamReader(in));
                     String strLine = new String();

                     length  = filee.length();

                     ProgressBar.setMaximum((int)length); //we're going to get this many bytes
                     ProgressBar.setValue(0); //we've gotten 0 bytes so far
                      //Read File Line By Line

                    font1 = new Font("Helvetica", Font.PLAIN, 18);
                    font1.isBold();
                    color = new Color( 74,118,110);
                    TextArea1.setForeground(color);
                    TextArea1.setFont(font1);

                     int soma=0;
                        while(in.readLine() != null)
                        {
                            strLine = in.readLine();  // reads from file
                            //System.out.println(strLine);


                            TextArea1.append(strLine+"\n");

                            pwOut.write(strLine);
                            pwOut.flush();

                            soma+=strLine.length()+1;
                            ProgressBar.setValue(ProgressBar.getValue()+(strLine.length()+1)*2);
                            ProgressBar.repaint();              
                        };

                        br.close();
                        pwOut.close();
                        Skt.close();
                }catch (Exception e){  System.err.println("Error: " + e.getMessage());  }
              }
            }.start();
    }

}
于 2012-10-17T17:39:40.283 に答える