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()获取套接字/流
  • 关闭服务器
  • 客户端

希望这能让您对它通常的外观有所了解。

于 2012-10-17T17:51:39.903 回答
0

好的,所以服务器是这样的:

公共类 KnockKnockServer { public static void main(String[] args) 抛出 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) 中读取单词并通过 Socket 发送时:

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 回答