2012-10-17 155 views
2

我遇到了套接字的一些问题。SOCKET处理并发服务器和客户端通信

我试图让一个并发服务器接受多个客户端。

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

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

CLIENT

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组件。 我认为所有的套接字都可以。为什么我不能在服务器端得到什么?

请帮

亲切的问候

+0

在我看来,你没有发布相关的代码。在服务器套接字上只有一行工作('Skt.close();') - 假设'Skt'是ServerSocket。请提供一个有意义的例子... – home

+0

对不起我的错误。服务器代码是较短的一个,客户端代码是标记为服务器的那个。 您希望我提供什么? –

回答

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()荷兰国际集团的插座/流
  • 关闭服务器
  • 的客户方

希望,让你关于它通常看起来如何的一些想法。

+0

是的,我错过了那一阵子,但我认为其余的都没问题..我想 –

+0

谢谢!非常简洁,非常有用! – Edeph

0

确定这样的服务器是这样的:

公共类KnockKnockServer { 公共静态无效的主要(字串[] 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(); } 

    } 
} 

在客户端中,唯一与w第i个服务器是当我读取来自词典文件(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(); 
    } 

}