当前位置: 首页 > 知识库问答 >
问题:

套接字处理并发服务器和客户端通信

芮明知
2023-03-14

我遇到一些插座的问题。

我正在尝试使一个并发服务器接受多个客户端。

当客户端连接到服务器时,服务器会创建一个新线程并侦听套接字。然后,如果客户端发送某些内容,服务器必须读取它。

在客户端,我只需打开一个字典(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();    }

请忘记秋千组件。我觉得所有插座都没问题。为什么我在服务器端什么都得不到?

请帮忙

亲切的问候

共有2个答案

孔飞舟
2023-03-14

服务器是这样的:

公共类KnockKnockServer{public静态空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();    }

    }
}

在Client中,与服务器交互的唯一事情是当我从字典文件(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();
    }

}
窦夜洛
2023-03-14

多线程服务器的一个简单示例:

//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
  }
}

本例中缺少:

  • 错误处理

希望这能让你对它通常的样子有所了解。

 类似资料:
  • 我对套接字有点陌生,我正在尝试编写一个程序,在这个程序中,我基本上可以从客户端程序向服务器程序发送一些简单的请求。现在我只想在客户端有1或2个选项供用户选择。例如,如果用户在客户端选择“选项1”,那么服务器会返回一条消息“您选择选项1”,以此类推,但我不知道如何读取服务器上从客户端发送的输入。 客户代码: 服务器代码: 我需要在Clinet中使用两个不同的BufferedReader吗?一个用于用

  • 问题内容: 我试图用没有gui的服务器连接带有gui的客户端。连接已完成,但我看不到这两个应用程序之间的任何消息。(我应该在客户端中找到SERVER HERE,在服务器中找到CLIENT HERE) 客户端连接代码: (输入和输出在此客户端类扩展到的GUI类中定义。定义为“受保护的BufferedReader输入;受保护的PrintWriter输出;”) 另外,服务器代码: 连接似乎还可以,所以我

  • 我正在尝试连接一个带有gui的客户端和一个没有gui的服务器。连接正在进行中,但我看不到这两个应用程序之间的任何消息。(我应该将服务器放在客户端中,而将客户端放在服务器中) 客户端连接代码: PS:我也在服务器中尝试了PrintWriter,也尝试了try catch in stream语句,问题仍然存在。

  • 我试图用java实现一个客户端服务器,在这里我读取客户端中的输入并在服务器中执行UperCase,然后返回客户端并打印UperCase。我使用ObjectOutputStream和ObjectInputStream进行读写,但是当我在客户机中键入一个msg时,程序会显示以下错误: Digite uma msg casa java.io.eofexception位于java.io.datainput

  • 问题内容: 我正在构建一个小型聊天应用程序,其中客户端A希望通过服务器B将某些东西发送到客户端C。首先,这是解决问题的正确方法吗?我能够向服务器发送数据或从服务器接收数据,但仅限于客户端。例如,如果客户端A向服务器B发送数据而客户端C向服务器B发送数据,则我可以将数据发送回服务器A和C就像回显服务器一样。但是我想要的是将来自客户端A的数据通过服务器B转发到客户端C。 以下是服务器代码: 客户端代码

  • 我有这个代码可以在eclipse中与android Studio中的客户端通信服务器,我使用套接字,客户端向服务器发送消息,服务器读取该消息并确定一切正常,但当服务器向客户端发送消息时,客户端不强制任何东西;这是代码 还有这个 此代码是服务器代码的一部分,如果您需要客户端代码(Android Studio),请告诉我。 我需要帮助拜托