很久没写博客了,这个本为课程设计,忙完了便抽空出来与大家分享一下,以便指正错误。
1、设计一个简单的聊天室程序。采用客户/服务器模式,分为客户端程序和服务器端程序。由于服务器只能支持一个客户,实际上是一个点对点通信的程序。客户端程序和服务器程序通过网络交换聊天字符串内容,并在窗口的列表框中显示。同时,实现了文件传输系统。
2、程序主界面(包含服务器端和客户端)。
3、先后点击监听和连接按钮即可建立互联。可以发送消息或传输文件。
4、其他不多说,直接上代码部分:
服务器:
public class chatServer extends JFrame implements Runnable,ActionListener{
/**
*
*/
private static final long serialVersionUID = -4929211394401993088L;
//private static final int SERVICE_PORT=13;
int SERVICE_PORT;
DataInputStream in;
DataOutputStream out;
ServerSocket server;
Socket nextClient;
JTextField textField,nameField,portField;
JTextArea textArea,textArea2;
JButton button,fButton;
JFileChooser chooser;
MyradioButton lisButton,disButton;
ButtonGroup group;
Font font = new Font("Adobe 黑体 Std",0,16);
JLabel label;
public chatServer() {
this.setTitle("Server");
init();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.setBounds(0, 0, 800, 500);
this.setResizable(false);
//this.setLocationRelativeTo(null);
//this.setUndecorated(true);
this.setLocation(1000,200);
this.setVisible(true);
}
@Override
public void run(){
try{
while(true){
System.out.println("Server Start!");
if(!lisButton.isSelected()) continue;
textArea.append("开始监听端口"+portField.getText()+"!\n");
SERVICE_PORT=Integer.valueOf(portField.getText()).intValue();
System.out.println("1");
server=new ServerSocket(SERVICE_PORT);
System.out.println("2");
nextClient = server.accept();
textArea.append("收到并接受客户端的连接请求!\n");
in=new DataInputStream(nextClient.getInputStream());
out=new DataOutputStream(nextClient.getOutputStream());
while (true){
String strUTF=in.readUTF();
if(strUTF.equals("&&close&&")) {disButton.setSelected(true);out.writeUTF("&&close&&");break;}
if(strUTF.equals("&&file.start&&"))
{
String fileName =in.readUTF();
chooser.setSelectedFile(new File(fileName));
int returnVal=chooser.showSaveDialog(this.getCon