如何实现java客户端循环接收服务器信息呢

来源:5-1 Socket 总结

qq_versatilewin_03747674

2016-08-09 22:19

想写一个简单的聊天程序,但是每次客户端只能接收服务器的第一条消息就无法接收了,找了一天也没找出问题,只能求助了,上代码。

-----------------Server类--------------------

package com.WindFamilyRain6;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {
static List<Socket> client=new ArrayList<Socket>();
static boolean keepRunning=true;
static int count=0;

 public static void main(String[] args) {
  // TODO Auto-generated method stub
try {
 
 ServerSocket serversocket=new ServerSocket(30000);  //创建服务器socket
 System.out.println("------------服务器已经启动,等待客户端连接----------");  //输出信息,表示建立成功
 /*
  * 持续监听客户端连接
  * 并输出已连接的客户端
  * 的相关信息
  */
 while(keepRunning){
 Socket socket=serversocket.accept();//接收客户端socket
 System.out.println("--------------已连接至一台客户端-----------------");
 client.add(socket);    //将其添加进client的List中
 System.out.println(client.get(count).toString());
 //启动此客户端的线程
 ServerThread serverthread=new ServerThread(socket);
 serverthread.setPriority(4);//设置优先级
 serverthread.start();
 count++;
 System.out.println("客户端数量:"+count);
 //获取客户端主机信息
 InetAddress address=socket.getInetAddress();
 System.out.println("客户端的主机名称为:"+address.getHostName());
 System.out.println("客户端的地址为:"+address.getHostAddress());
 }
 serversocket.close();
} catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}

 

}
}

---------------ServerThread类------------

package com.WindFamilyRain6;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread extends Thread {
Socket socket;
OutputStream os;
PrintWriter pw;
InputStream is;
BufferedReader br;
String MassageByReceive="dsa";
 public ServerThread(Socket socket){
 this.socket=socket;
}
 public void run(){
 try {
  os=socket.getOutputStream();//获取客户端输出流
  os.write("连接成功......\n".getBytes());//输出信息以提示已连接至服务器
  os.write("操你来来".getBytes());
  os.flush();
  is=socket.getInputStream();//获取客户端输入流
  br=new BufferedReader(new InputStreamReader(is));//包装为字符流并添加缓冲
  while(true){
   System.out.println(br.ready());
   MassageByReceive=br.readLine(); //读取客户端信息并保存至字符串
   //for each遍历list中所有客户端,并转发消息至所有客户端
   for (Socket client : Server.client) {
    os=client.getOutputStream();//获取输出流
    pw=new PrintWriter(os);//包装为打印流
    pw.write(MassageByReceive);//发送消息至客户端
    pw.flush();//刷新缓冲
    System.out.println(MassageByReceive);
   }
   sleep(100);
  }
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 
 }
}

--------------clientFrame类---------------

package com.WindFamilyRain6;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;

public class ClientFrame extends JFrame {
private String name="小红";
 private JPanel contentPane;
 private JTextField text_name;
 private JTextField textField;
 static Socket socket;
  protected static JTextArea textArea_chatArea;
  InputStream is;
 BufferedReader br;
 OutputStream os;
 PrintWriter pw;
 String MassageForSend;
/**
 * receiveMassage方法用于接收服务器传来的消息
 * 并打印至聊天框中
 */
 

 
 public static void main(String[] args) {
  
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     ClientFrame frame = new ClientFrame();
     frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }); 
  try {
   socket=new Socket("192.168.1.102",30000);//创建客户端socket
   
  } catch (UnknownHostException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  ClientThread clientthread=new ClientThread(socket);
  clientthread.start();
 }

 /**
  * Create the frame.
  */
 public ClientFrame() {
 
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 450, 300);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  
  JLabel label = new JLabel("\u6635\u79F0\uFF1A");
  label.setFont(new Font("华文楷体", Font.PLAIN, 17));
  
  text_name = new JTextField();
  text_name.setBackground(Color.WHITE);
  text_name.setForeground(Color.BLACK);
  text_name.setEditable(false);
  text_name.setColumns(10);
  text_name.setText(name);
  
  textArea_chatArea = new JTextArea();
  
  JLabel lblNewLabel = new JLabel("\u8BF7\u8F93\u5165\u804A\u5929\u5185\u5BB9\uFF1A");
  lblNewLabel.setFont(new Font("华文楷体", Font.PLAIN, 19));
  
  textField = new JTextField();
  textField.setColumns(10);
  
  JButton Button_send = new JButton("\u53D1\u9001");
  //添加按钮响应事件用于发送消息至客户端
  Button_send.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    try {
     os=socket.getOutputStream();//获取输出流
     pw=new PrintWriter(os);//包装为打印流
     MassageForSend=name+":"+textField.getText()+"\n";  //保存客户端消息至字符串
     pw.write(MassageForSend);//发送消息至客户端
     pw.flush();//刷新缓冲
     textField.setText("");
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }

    
   }
  });
  GroupLayout gl_contentPane = new GroupLayout(contentPane);
  gl_contentPane.setHorizontalGroup(
   gl_contentPane.createParallelGroup(Alignment.LEADING)
    .addGroup(gl_contentPane.createSequentialGroup()
     .addGap(41)
     .addComponent(label, GroupLayout.PREFERRED_SIZE, 61, GroupLayout.PREFERRED_SIZE)
     .addPreferredGap(ComponentPlacement.RELATED)
     .addComponent(text_name, GroupLayout.PREFERRED_SIZE, 146, GroupLayout.PREFERRED_SIZE)
     .addContainerGap(220, Short.MAX_VALUE))
    .addComponent(textArea_chatArea, GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)
    .addGroup(gl_contentPane.createSequentialGroup()
     .addComponent(lblNewLabel)
     .addPreferredGap(ComponentPlacement.RELATED)
     .addComponent(textField, GroupLayout.PREFERRED_SIZE, 181, GroupLayout.PREFERRED_SIZE)
     .addPreferredGap(ComponentPlacement.RELATED)
     .addComponent(Button_send, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)
     .addGap(57))
  );
  gl_contentPane.setVerticalGroup(
   gl_contentPane.createParallelGroup(Alignment.LEADING)
    .addGroup(gl_contentPane.createSequentialGroup()
     .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
      .addComponent(label, GroupLayout.PREFERRED_SIZE, 28, GroupLayout.PREFERRED_SIZE)
      .addComponent(text_name, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
     .addPreferredGap(ComponentPlacement.RELATED)
     .addComponent(textArea_chatArea, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
     .addPreferredGap(ComponentPlacement.UNRELATED)
     .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
      .addComponent(lblNewLabel)
      .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
      .addComponent(Button_send))
     .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
  );
  contentPane.setLayout(gl_contentPane);
 }
}

----------------clientThread类---------------------

package com.WindFamilyRain6;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class ClientThread extends Thread {
 Socket socket;

 String MassageByReceive;
public ClientThread(Socket socket){
 this.socket=socket;
}
public void run(){
 try {
  InputStream is=socket.getInputStream();
  BufferedReader bf=new BufferedReader(new InputStreamReader(is));
  while(true){
   MassageByReceive=bf.readLine();
   System.out.println(bf.ready());
   System.out.println(MassageByReceive);
   sleep(100);
  }
 }catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}
}

谢谢啦

写回答 关注

1回答

  • qq_慕侠1535465
    2016-08-11 16:52:21

    while(true){

    }

Java Socket应用---通信是这样练成的

分享的是 Java 中的网络编程,使用Socket实现网络聊天通信

125013 学习 · 590 问题

查看课程

相似问题