JAVA socket 编程 基于JAVA socket的客户/服务器模式,客户端我放了三个按钮单击不同的按钮向服务器发送不同的消息(消息为字符串),运行时发现只能发送一次,再单击其他按钮就不行了~高手帮忙给个解决方法啊,急求!! 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 定义一个flag例如:button1,button2,button3 默认为false当按下某一button时置改button为TRUEif(button1==true){ ...... button1=false; }else if(button2==TRUE){ ...... button2=false;}else{button3==true){...... button3=false;} 我正好做过socket编程,但是不大明白你说的意思,可否详细点?我觉得可能有关的两个地方是:连接的建立与断开的对应,接受是否同步 你说是点击其中一个按钮其他按钮就不能使用了强烈建议你使用jQuery来实现,你随便网上搜搜,比较简单当然编写触发事件也是可以实现的 下面是服务器端:1;主界面import java.applet.*;import java.awt.*;import java.awt.event.*;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;import java.util.StringTokenizer;import javax.swing.*;//创建一个窗口public class ServermainFrame extends JFrame implements ActionListener{ public static String s; ServerSocket serverSocket; JButton show,connect,cancel; JTextField message; JPanel sharePanel; GridBagLayout gridBag; GridBagConstraints gridBagCon;// 设置框架大小 Dimension framesize=new Dimension(300,200); //构造方法 public ServermainFrame() { // 添加关闭 // this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); //this.pack(); show=new JButton("显示共享文件列表"); connect=new JButton("链接"); cancel=new JButton("断开"); message=new JTextField(12); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); this.pack(); //添加框架大小 this.setSize(framesize); this.setVisible(true); //设置运行时窗口位置 //设置运行时位置 Dimension screenSize= Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation((int)(screenSize.width - framesize.getWidth())/2,(int)(screenSize.height - framesize.getHeight())/2); this.setResizable(true); this.setTitle("服务器"); Container contentPane=getContentPane(); //Container con=new Container(),界面无法显示 contentPane.setLayout(new BorderLayout()); // 布局设置 sharePanel=new JPanel(); gridBag=new GridBagLayout(); sharePanel.setLayout(gridBag); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=0; gridBagCon.gridy=0; gridBagCon.gridheight=2; gridBagCon.gridwidth=4; gridBagCon.ipadx=4; gridBagCon.ipady=4; JLabel none=new JLabel(); gridBag.setConstraints(none, gridBagCon); sharePanel.add(none); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=0; gridBagCon.gridy=2; gridBagCon.gridwidth=2; gridBagCon.gridheight=1; //gridBagCon.insets=new Insets(1,0,0,0); gridBag.setConstraints(show, gridBagCon); // sharePanel.add(show); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=0; gridBagCon.gridy=3; gridBagCon.gridwidth=4; gridBagCon.gridheight=1; gridBag.setConstraints(message, gridBagCon); // sharePanel.add(message); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=0; gridBagCon.gridy=4; gridBagCon.gridwidth=2; gridBagCon.gridheight=1; gridBagCon.insets=new Insets(1,0,0,0); gridBagCon.anchor=GridBagConstraints.LINE_START; gridBag.setConstraints(connect,gridBagCon); sharePanel.add(connect); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=2; gridBagCon.gridy=4; gridBagCon.gridwidth=2; gridBagCon.gridheight=1; gridBagCon.anchor=GridBagConstraints.LINE_START; gridBag.setConstraints(cancel,gridBagCon); sharePanel.add(cancel); contentPane.add(sharePanel,BorderLayout.CENTER ); setVisible(true); connect.addActionListener(this); cancel.addActionListener(this); show.addActionListener(this); }//gouzao public void actionPerformed(ActionEvent e) { Object obj=e.getSource(); if(obj==connect) { starServer s =new starServer(); //启动服务器 } else if(obj==cancel) { System.out.println("cancel"); int j=JOptionPane.showConfirmDialog(this, "真的停止服务吗","停止服务",JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE); if (j==JOptionPane.YES_OPTION){ try{ serverSocket.close(); message.setText("服务器已关闭"); }//try catch(Exception g){ System.out.println(g); } } } }//action public static void main(String[] args) { ServermainFrame servermainframe=new ServermainFrame(); servermainframe.setVisible(true); } }//Server 2启动服务器import java.io.*;import java.net.*;import java.applet.Applet;import java.util.*; class starServer{ public starServer(){ ServerSocket rServer=null; Socket request=null; //请求套接字 Thread receiveThread=null; try{ rServer=new ServerSocket(4600); System.out.println("Welcome to Server"); while(true){ request=rServer.accept(); receiveThread=new serverThread(request);//生成serverThread实例 receiveThread.start();//启动serverThread线程 }//while }catch(IOException e){ System.out.println(e.getMessage()); } }//ServerShare() }3:服务器运行:import java.io.*;import java.net.*;import java.applet.Applet;import java.util.*;class serverThread extends Thread{ String test; Socket clientRequest;//用户连接的套接字 BufferedReader input; PrintWriter output; public serverThread(Socket s){ this.clientRequest=s; try{ BufferedReader input=new BufferedReader(new InputStreamReader(clientRequest.getInputStream())); // PrintWriter output=new PrintWriter(clientRequest.getOutputStream()); test=input.readLine(); System.out.println("Client:"+test); }catch(IOException e){ System.out.println(e.getMessage());} }//serverThread() public void run(){ try{ PrintWriter output=new PrintWriter(clientRequest.getOutputStream()); StringTokenizer tokenizer; tokenizer=new StringTokenizer(test); String sign=tokenizer.nextToken(); //不能用tokenizer.nextToken()直接去比较“0”,“1”。要先赋给一个变量,用该变量去比较,否则只能运行第一项 if(sign.equals("1")) { String searchcontent=tokenizer.nextToken(); System.out.println("search"+" "+searchcontent); String result="we find it"; output.println(result); output.flush(); //搜索 } else if(sign.equals("0")) { output.println("上传成功"); output.flush(); }//equals 0 }catch(IOException e){System.out.println("server thread error");} }//run }//serverThread打开服务器后,客户端这边先设定一个端口然后连接。然后在搜索栏里填入要搜索的内容,单击“搜索”,能运行。但是再单击“上传”,就不能运行了。同样,先单击“上传”能运行,在“搜索”又不行了~我想的是两个都能运行,高手帮忙看看啊,多谢了!! 这是我的客户端代码:import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import java.io.*;import java.net.*;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.StringTokenizer;public class mainFrame extends JFrame implements ActionListener { /** * @param args */ public static String getfileName,getfileLocate; //获取要共享的文件名和路径 String searchfilename; String savePort; //保存设置的端口号 String messageToServer; String resultFromServer; //搜索结果 String upresult; //上传结果 JTextArea message; JScrollPane messageScrollPane; //显示消息 JLabel source,downprocess,downtime,showspeed; //搜索内容,选取资源,下载进程,剩余时间 JTextField searchshow,sourceshow,processshow,timeshow,showstatus; //显示内容 JButton search,down; //JFileChooser jfc;//打开下载文件目录 Socket socket; PrintWriter os; BufferedReader is; //建立菜单栏 JMenuBar jMenubar=new JMenuBar(); //菜单组 JMenu fileoperate=new JMenu("文件"); JMenu downoperate=new JMenu("操作"); JMenu helptxt=new JMenu("帮助"); JMenu check=new JMenu("查看"); JMenu function=new JMenu("功能"); //菜单项 JMenuItem upfile=new JMenuItem("选择上传文件"); JMenuItem downfile=new JMenuItem("保存路径"); JMenuItem downstop=new JMenuItem("暂停下载"); JMenuItem downcancel=new JMenuItem("取消下载"); JMenuItem checksharefile=new JMenuItem("共享文件列表"); JMenuItem checkdownfile=new JMenuItem("下载文件列表"); JMenuItem sharefileB=new JMenuItem("上传"); JMenuItem sharefiledown=new JMenuItem("下传"); JMenuItem connect=new JMenuItem("连接"); JMenuItem disConnect=new JMenuItem("断开"); JMenuItem textsearch=new JMenuItem("搜索"); JMenuItem textdown=new JMenuItem("下载"); JMenuItem setport=new JMenuItem("设置端口"); JMenuItem serversharefile=new JMenuItem("服务器共享文件"); JMenuItem systemIn=new JMenuItem("系统说明"); JMenuItem tous=new JMenuItem("联系我们"); JMenuItem aboutSystem=new JMenuItem("关于"); //建立工具栏 JToolBar toolBar=new JToolBar(); //建立工具栏中的按钮 JButton connectServer=new JButton("连接"); JButton setPort=new JButton("设置端口"); JButton upButton=new JButton("上传"); JButton disconnect=new JButton("断开"); JButton filedown=new JButton("下传"); JButton savePath=new JButton("保存路径"); //设置框架大小 Dimension framesize=new Dimension(400,600); JPanel downPanel; GridBagLayout gridBag; GridBagConstraints gridBagCon; public mainFrame() { //程序初始化 init(); //显示当前时间 //添加关闭 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); this.pack(); //添加框架大小 this.setSize(framesize); this.setVisible(true); //设置运行时窗口位置 Dimension screenSize= Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation((int)(screenSize.width - framesize.getWidth())/2,(int)(screenSize.height - framesize.getHeight())/2); this.setResizable(true); this.setTitle("客户端下载"); } public void init(){ Container contentPane=getContentPane(); //Container con=new Container(),界面无法显示 contentPane.setLayout(new BorderLayout()); //添加菜单栏 fileoperate.add(upfile); fileoperate.addSeparator(); fileoperate.add(downfile); jMenubar.add(fileoperate); downoperate.add(downstop); downoperate.addSeparator(); downoperate.add(downcancel); downoperate.addSeparator(); downoperate.add(connect); downoperate.addSeparator(); downoperate.add(disConnect); jMenubar.add(downoperate); check.add(serversharefile); check.addSeparator(); check.add(checksharefile); check.addSeparator(); check.add(checkdownfile); jMenubar.add(check); function.add(sharefileB); function.addSeparator(); function.add(sharefiledown); function.addSeparator(); function.add(textsearch); function.addSeparator(); function.add(textdown); function.addSeparator(); function.add(setport); jMenubar.add(function); helptxt.add(systemIn); helptxt.addSeparator(); helptxt.add(tous); helptxt.addSeparator(); helptxt.add(aboutSystem); jMenubar.add(helptxt); setJMenuBar(jMenubar); //添加工具栏 toolBar.add(setPort); toolBar.addSeparator(); //添加分隔栏 toolBar.add(connectServer); toolBar.addSeparator(); toolBar.add(upButton); toolBar.addSeparator(); toolBar.add(filedown); toolBar.addSeparator(); toolBar.add(disconnect); toolBar.addSeparator(); toolBar.add(savePath); contentPane.add(toolBar,BorderLayout.NORTH ); //为工具栏按钮添加事件监听 filedown.addActionListener(this); setPort.addActionListener(this); connectServer.addActionListener(this); upButton.addActionListener(this); savePath.addActionListener(this); disconnect.addActionListener(this); message=new JTextArea(); message.setEditable(false); //添加滚动条 messageScrollPane=new JScrollPane(message, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); messageScrollPane.setPreferredSize(new Dimension(400,400)); messageScrollPane.revalidate(); searchshow=new JTextField(23); sourceshow=new JTextField(20); searchshow.setEnabled(true); sourceshow.setEnabled(true); search=new JButton("搜索"); down=new JButton("下载"); searchshow.addActionListener(this); search.addActionListener(this); sourceshow.addActionListener(this); down.addActionListener(this); source=new JLabel("资源"); downprocess=new JLabel("下载进度"); downtime=new JLabel("下载速度"); showspeed=new JLabel(); processshow=new JTextField(7); timeshow=new JTextField(7); showstatus=new JTextField(23); //布局设置 downPanel=new JPanel(); gridBag=new GridBagLayout(); downPanel.setLayout(gridBag); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=0; gridBagCon.gridy=0; gridBagCon.gridheight=2; gridBagCon.gridwidth=5; gridBagCon.ipadx=5; gridBagCon.ipady=5; JLabel none=new JLabel(); gridBag.setConstraints(none, gridBagCon); downPanel.add(none); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=0; gridBagCon.gridy=2; gridBagCon.gridwidth=3; gridBagCon.gridheight=1; gridBagCon.insets=new Insets(1,0,0,0); gridBag.setConstraints(searchshow, gridBagCon); // downPanel.add(searchshow); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=3; gridBagCon.gridy=2; gridBag.setConstraints(search, gridBagCon); downPanel.add(search); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=0; gridBagCon.gridy=3; gridBagCon.anchor=GridBagConstraints.LINE_START; gridBag.setConstraints(source,gridBagCon); downPanel.add(source); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=1; gridBagCon.gridy=3; gridBagCon.gridwidth=2; gridBagCon.gridheight=1; gridBagCon.insets=new Insets(1,0,0,0); gridBag.setConstraints(sourceshow, gridBagCon); downPanel.add(sourceshow); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=3; gridBagCon.gridy=3; gridBagCon.insets=new Insets(1,0,0,0); gridBag.setConstraints(down, gridBagCon); downPanel.add(down); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=0; gridBagCon.gridy=4; //gridBagCon.insets=new Insets(1,0,0,0); gridBag.setConstraints(downprocess, gridBagCon); downPanel.add(downprocess); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=2; gridBagCon.gridy=4; gridBagCon.insets=new Insets(1,0,0,0); gridBag.setConstraints(downtime, gridBagCon); downPanel.add(downtime); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=3; gridBagCon.gridy=4; gridBagCon.insets=new Insets(1,0,0,0); gridBag.setConstraints(showspeed, gridBagCon); downPanel.add(showspeed); showstatus=new JTextField(35); showstatus.setEditable(false); gridBagCon=new GridBagConstraints(); gridBagCon.gridx=0; gridBagCon.gridy=5; gridBagCon.gridwidth=5; gridBag.setConstraints(showstatus, gridBagCon); downPanel.add(showstatus); contentPane.add(messageScrollPane,BorderLayout.CENTER); contentPane.add(downPanel,BorderLayout.SOUTH); } 问问题不太得要领啊,你贴了这么多代码:search=new JButton("搜索"); search.addActionListener(this); 可是你贴出来的代码,却不包含actionPerformed相关的逻辑,呵呵,怎么查? 还有这段没贴上//事件处理 public void actionPerformed(ActionEvent e) { Object obj=e.getSource(); //获得事件类型 if(obj==setPort||obj==setport) { String inputValue = JOptionPane.showInputDialog("请输入端口号"); // sourceshow.setText(inputValue); double i=Double.parseDouble(inputValue); if((i>1&&i<1024)||i>65535){ JOptionPane.showMessageDialog(null, "端口应介于1024-65535", "端口错误", JOptionPane.ERROR_MESSAGE); } else savePort=inputValue; } //设置客户端端口并判断端口是否越界 else if(obj==connectServer||obj==connect) { if(savePort==null) { JOptionPane.showMessageDialog(null, "未设置端口", "连接服务器", JOptionPane.ERROR_MESSAGE); } //ConnectServer(); // 连接服务器 else { try{ socket=new Socket("127.0.0.1",4600);//注意两端的端口号必须一致 System.out.println("Connection!!"); os=new PrintWriter(socket.getOutputStream());// 由Socket对象得到输出流,发往服务器端的消息 } catch(Exception i){ System.out.print("not connect"); } } }//设置连接服务器 else if(obj==disconnect||obj==disConnect){ if(socket.isClosed()){ return; } try{ // os.close(); // is.close(); socket.close(); // message.append("与服务器断开连接"); System.out.println("disconnect"); } catch(Exception j){ } }//断开连接 else if(obj==search||obj==textsearch) { try{ String sea="1"; //设定标识符,“1”为搜索的内容 searchfilename=searchshow.getText(); messageToServer=sea+" "+searchfilename; is=new BufferedReader(new InputStreamReader(socket.getInputStream())); os.println(messageToServer); os.flush(); resultFromServer=is.readLine(); sourceshow.setText(resultFromServer); }catch(Exception i){ System.out.println("search error"); } }//搜索资源 else if(obj==upButton||obj==sharefileB){ try{ String clientIp=InetAddress.getLocalHost().getHostAddress(); //获取客户端的IP地址 is=new BufferedReader(new InputStreamReader(socket.getInputStream())); String up="0"; //设定标识符,“0”为上传的内容 //获取 端口,文件名,文件路径 messageToServer =up+" "+clientIp; System.out.println(messageToServer); os.println(messageToServer); //向服务器发送消息 os.flush(); upresult=is.readLine(); sourceshow.setText(upresult); }catch(Exception i){ System.out.print("upfile error"); } }//上传文件 } public static void main(String[] args) { mainFrame mainframe=new mainFrame(); mainframe.setVisible(true); mainframe.setResizable(false); //窗口不可伸缩 }} 恩,为查这个问题真不容易。代码好多啊。你的通信模型有点问题,你的客户端是点击“链接”的时候建立到服务器的socket,后续的查询、上传、下载都是使用该Socket,但你的serverThread这个类(作为一个服务线程)的run函数中,没有循环接收客户端的指令,所以,客户端发送一次请求后,服务线程就退出了:public void run() { try { PrintWriter output = new PrintWriter(clientRequest.getOutputStream()); StringTokenizer tokenizer; tokenizer = new StringTokenizer(test); String sign = tokenizer.nextToken(); //不能用tokenizer.nextToken()直接去比较“0”,“1”。要先赋给一个变量,用该变量去比较,否则只能运行第一项 if (sign.equals("1")) { String searchcontent = tokenizer.nextToken(); System.out.println("search" + " " + searchcontent); String result = "we find it"; output.println(result); output.flush(); //搜索 }else if (sign.equals("0")) { output.println("上传成功"); output.flush(); }//equals 0 } catch (IOException e) { System.out.println("server thread error"); } //处理一次请求,该方法退出,也就意味着线程退出了,无法再接收更多的服务 }//run 改进方法有两个:1、在这个服务线程的run方法中写一个while(true)循环,不断的接收客户端的请求,然后在客户端增加一个“断开”按钮,当发送断开指令时,服务线程用break退出该死循环2、你的客户端改造成每次请求“先链接-发出请求-接收结果-断开链接”的模式,就像HTTP协议一样。 java单链表中间添加节点 有关JAVA管理流程方面的问题 Jtable 问题 java往access数据库中插入不进去记录 Lava-Lava的源代码哪里有下载?? java的crawler 有什么? j2sdk1-4_2_01安装后的环境配置和CLASSPATH是怎么设置的? 捕获异常后为什么又出现找不到符号的错误? protect的访问权限? 一个母子对话框关系的问题 初学者的类型问题 为什么JFrame的setVisible的默认值为false
当按下某一button时置改button为TRUE
if(button1==true)
{
......
button1=false;
}
else if(button2==TRUE)
{
......
button2=false;
}
else{button3==true)
{
......
button3=false;
}
我觉得可能有关的两个地方是:
连接的建立与断开的对应,接受是否同步
强烈建议你使用jQuery来实现,你随便网上搜搜,比较简单
当然编写触发事件也是可以实现的
下面是服务器端:
1;主界面import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;import javax.swing.*;//创建一个窗口public class ServermainFrame extends JFrame implements ActionListener
{
public static String s;
ServerSocket serverSocket;
JButton show,connect,cancel;
JTextField message;
JPanel sharePanel;
GridBagLayout gridBag;
GridBagConstraints gridBagCon;
// 设置框架大小
Dimension framesize=new Dimension(300,200);
//构造方法 public ServermainFrame()
{
// 添加关闭
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
//this.pack();
show=new JButton("显示共享文件列表");
connect=new JButton("链接");
cancel=new JButton("断开");
message=new JTextField(12);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
this.pack();
//添加框架大小
this.setSize(framesize);
this.setVisible(true);
//设置运行时窗口位置
//设置运行时位置
Dimension screenSize=
Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation((int)(screenSize.width - framesize.getWidth())/2,(int)(screenSize.height - framesize.getHeight())/2);
this.setResizable(true);
this.setTitle("服务器");
Container contentPane=getContentPane(); //Container con=new Container(),界面无法显示
contentPane.setLayout(new BorderLayout());
// 布局设置
sharePanel=new JPanel();
gridBag=new GridBagLayout();
sharePanel.setLayout(gridBag);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=0;
gridBagCon.gridy=0;
gridBagCon.gridheight=2;
gridBagCon.gridwidth=4;
gridBagCon.ipadx=4;
gridBagCon.ipady=4;
JLabel none=new JLabel();
gridBag.setConstraints(none, gridBagCon);
sharePanel.add(none);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=0;
gridBagCon.gridy=2;
gridBagCon.gridwidth=2;
gridBagCon.gridheight=1;
//gridBagCon.insets=new Insets(1,0,0,0);
gridBag.setConstraints(show, gridBagCon); //
sharePanel.add(show);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=0;
gridBagCon.gridy=3;
gridBagCon.gridwidth=4;
gridBagCon.gridheight=1;
gridBag.setConstraints(message, gridBagCon); //
sharePanel.add(message);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=0;
gridBagCon.gridy=4;
gridBagCon.gridwidth=2;
gridBagCon.gridheight=1;
gridBagCon.insets=new Insets(1,0,0,0);
gridBagCon.anchor=GridBagConstraints.LINE_START;
gridBag.setConstraints(connect,gridBagCon);
sharePanel.add(connect);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=2;
gridBagCon.gridy=4;
gridBagCon.gridwidth=2;
gridBagCon.gridheight=1;
gridBagCon.anchor=GridBagConstraints.LINE_START;
gridBag.setConstraints(cancel,gridBagCon);
sharePanel.add(cancel);
contentPane.add(sharePanel,BorderLayout.CENTER );
setVisible(true);
connect.addActionListener(this);
cancel.addActionListener(this);
show.addActionListener(this);
}//gouzao
public void actionPerformed(ActionEvent e)
{
Object obj=e.getSource();
if(obj==connect)
{
starServer s =new starServer(); //启动服务器
}
else if(obj==cancel)
{
System.out.println("cancel");
int j=JOptionPane.showConfirmDialog(this, "真的停止服务吗","停止服务",JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE);
if (j==JOptionPane.YES_OPTION){
try{
serverSocket.close();
message.setText("服务器已关闭");
}//try
catch(Exception g){
System.out.println(g);
}
}
}
}//action
public static void main(String[] args) {
ServermainFrame servermainframe=new ServermainFrame();
servermainframe.setVisible(true);
}
}//Server
2启动服务器
import java.io.*;
import java.net.*;
import java.applet.Applet;
import java.util.*;
class starServer{
public starServer(){
ServerSocket rServer=null;
Socket request=null; //请求套接字
Thread receiveThread=null;
try{
rServer=new ServerSocket(4600);
System.out.println("Welcome to Server");
while(true){
request=rServer.accept();
receiveThread=new serverThread(request);//生成serverThread实例
receiveThread.start();//启动serverThread线程
}//while
}catch(IOException e){
System.out.println(e.getMessage());
}
}//ServerShare()
}
3:服务器运行:import java.io.*;
import java.net.*;
import java.applet.Applet;
import java.util.*;
class serverThread extends Thread{
String test;
Socket clientRequest;//用户连接的套接字
BufferedReader input;
PrintWriter output;
public serverThread(Socket s){
this.clientRequest=s;
try{
BufferedReader input=new BufferedReader(new
InputStreamReader(clientRequest.getInputStream()));
// PrintWriter output=new PrintWriter(clientRequest.getOutputStream());
test=input.readLine();
System.out.println("Client:"+test);
}catch(IOException e){
System.out.println(e.getMessage());}
}//serverThread()
public void run(){
try{
PrintWriter output=new PrintWriter(clientRequest.getOutputStream());
StringTokenizer tokenizer;
tokenizer=new StringTokenizer(test);
String sign=tokenizer.nextToken(); //不能用tokenizer.nextToken()直接去比较“0”,“1”。要先赋给一个变量,用该变量去比较,否则只能运行第一项
if(sign.equals("1"))
{
String searchcontent=tokenizer.nextToken();
System.out.println("search"+" "+searchcontent);
String result="we find it";
output.println(result);
output.flush();
//搜索
}
else if(sign.equals("0"))
{
output.println("上传成功");
output.flush();
}//equals 0
}catch(IOException e){System.out.println("server thread error");}
}//run
}//serverThread打开服务器后,客户端这边先设定一个端口然后连接。然后在搜索栏里填入要搜索的内容,单击“搜索”,能运行。但是再单击“上传”,就不能运行了。同样,先单击“上传”能运行,在“搜索”又不行了~我想的是两个都能运行,高手帮忙看看啊,多谢了!!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;public class mainFrame extends JFrame implements ActionListener { /**
* @param args
*/
public static String getfileName,getfileLocate; //获取要共享的文件名和路径
String searchfilename;
String savePort; //保存设置的端口号
String messageToServer;
String resultFromServer; //搜索结果
String upresult; //上传结果
JTextArea message;
JScrollPane messageScrollPane; //显示消息
JLabel source,downprocess,downtime,showspeed; //搜索内容,选取资源,下载进程,剩余时间
JTextField searchshow,sourceshow,processshow,timeshow,showstatus; //显示内容
JButton search,down;
//JFileChooser jfc;//打开下载文件目录
Socket socket;
PrintWriter os;
BufferedReader is;
//建立菜单栏
JMenuBar jMenubar=new JMenuBar();
//菜单组
JMenu fileoperate=new JMenu("文件");
JMenu downoperate=new JMenu("操作");
JMenu helptxt=new JMenu("帮助");
JMenu check=new JMenu("查看");
JMenu function=new JMenu("功能");
//菜单项
JMenuItem upfile=new JMenuItem("选择上传文件");
JMenuItem downfile=new JMenuItem("保存路径");
JMenuItem downstop=new JMenuItem("暂停下载");
JMenuItem downcancel=new JMenuItem("取消下载");
JMenuItem checksharefile=new JMenuItem("共享文件列表");
JMenuItem checkdownfile=new JMenuItem("下载文件列表");
JMenuItem sharefileB=new JMenuItem("上传");
JMenuItem sharefiledown=new JMenuItem("下传");
JMenuItem connect=new JMenuItem("连接");
JMenuItem disConnect=new JMenuItem("断开");
JMenuItem textsearch=new JMenuItem("搜索");
JMenuItem textdown=new JMenuItem("下载");
JMenuItem setport=new JMenuItem("设置端口");
JMenuItem serversharefile=new JMenuItem("服务器共享文件");
JMenuItem systemIn=new JMenuItem("系统说明");
JMenuItem tous=new JMenuItem("联系我们");
JMenuItem aboutSystem=new JMenuItem("关于");
//建立工具栏
JToolBar toolBar=new JToolBar();
//建立工具栏中的按钮
JButton connectServer=new JButton("连接");
JButton setPort=new JButton("设置端口");
JButton upButton=new JButton("上传");
JButton disconnect=new JButton("断开");
JButton filedown=new JButton("下传");
JButton savePath=new JButton("保存路径");
//设置框架大小
Dimension framesize=new Dimension(400,600);
JPanel downPanel;
GridBagLayout gridBag;
GridBagConstraints gridBagCon;
public mainFrame()
{ //程序初始化
init();
//显示当前时间
//添加关闭
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
this.pack();
//添加框架大小
this.setSize(framesize);
this.setVisible(true);
//设置运行时窗口位置
Dimension screenSize=
Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation((int)(screenSize.width - framesize.getWidth())/2,(int)(screenSize.height - framesize.getHeight())/2);
this.setResizable(true);
this.setTitle("客户端下载");
}
Container contentPane=getContentPane(); //Container con=new Container(),界面无法显示
contentPane.setLayout(new BorderLayout());
//添加菜单栏
fileoperate.add(upfile);
fileoperate.addSeparator();
fileoperate.add(downfile);
jMenubar.add(fileoperate);
downoperate.add(downstop);
downoperate.addSeparator();
downoperate.add(downcancel);
downoperate.addSeparator();
downoperate.add(connect);
downoperate.addSeparator();
downoperate.add(disConnect);
jMenubar.add(downoperate);
check.add(serversharefile);
check.addSeparator();
check.add(checksharefile);
check.addSeparator();
check.add(checkdownfile);
jMenubar.add(check);
function.add(sharefileB);
function.addSeparator();
function.add(sharefiledown);
function.addSeparator();
function.add(textsearch);
function.addSeparator();
function.add(textdown);
function.addSeparator();
function.add(setport);
jMenubar.add(function);
helptxt.add(systemIn);
helptxt.addSeparator();
helptxt.add(tous);
helptxt.addSeparator();
helptxt.add(aboutSystem);
jMenubar.add(helptxt);
setJMenuBar(jMenubar);
//添加工具栏
toolBar.add(setPort);
toolBar.addSeparator(); //添加分隔栏
toolBar.add(connectServer);
toolBar.addSeparator();
toolBar.add(upButton);
toolBar.addSeparator();
toolBar.add(filedown);
toolBar.addSeparator();
toolBar.add(disconnect);
toolBar.addSeparator();
toolBar.add(savePath);
contentPane.add(toolBar,BorderLayout.NORTH );
//为工具栏按钮添加事件监听
filedown.addActionListener(this);
setPort.addActionListener(this);
connectServer.addActionListener(this);
upButton.addActionListener(this);
savePath.addActionListener(this);
disconnect.addActionListener(this);
message=new JTextArea();
message.setEditable(false);
//添加滚动条
messageScrollPane=new JScrollPane(message,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
messageScrollPane.setPreferredSize(new Dimension(400,400));
messageScrollPane.revalidate();
searchshow=new JTextField(23);
sourceshow=new JTextField(20);
searchshow.setEnabled(true);
sourceshow.setEnabled(true);
search=new JButton("搜索");
down=new JButton("下载");
searchshow.addActionListener(this);
search.addActionListener(this);
sourceshow.addActionListener(this);
down.addActionListener(this);
source=new JLabel("资源");
downprocess=new JLabel("下载进度");
downtime=new JLabel("下载速度");
showspeed=new JLabel();
processshow=new JTextField(7);
timeshow=new JTextField(7);
showstatus=new JTextField(23);
//布局设置
downPanel=new JPanel();
gridBag=new GridBagLayout();
downPanel.setLayout(gridBag);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=0;
gridBagCon.gridy=0;
gridBagCon.gridheight=2;
gridBagCon.gridwidth=5;
gridBagCon.ipadx=5;
gridBagCon.ipady=5;
JLabel none=new JLabel();
gridBag.setConstraints(none, gridBagCon);
downPanel.add(none);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=0;
gridBagCon.gridy=2;
gridBagCon.gridwidth=3;
gridBagCon.gridheight=1;
gridBagCon.insets=new Insets(1,0,0,0);
gridBag.setConstraints(searchshow, gridBagCon); //
downPanel.add(searchshow);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=3;
gridBagCon.gridy=2;
gridBag.setConstraints(search, gridBagCon);
downPanel.add(search);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=0;
gridBagCon.gridy=3;
gridBagCon.anchor=GridBagConstraints.LINE_START;
gridBag.setConstraints(source,gridBagCon);
downPanel.add(source);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=1;
gridBagCon.gridy=3;
gridBagCon.gridwidth=2;
gridBagCon.gridheight=1;
gridBagCon.insets=new Insets(1,0,0,0);
gridBag.setConstraints(sourceshow, gridBagCon);
downPanel.add(sourceshow);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=3;
gridBagCon.gridy=3;
gridBagCon.insets=new Insets(1,0,0,0);
gridBag.setConstraints(down, gridBagCon);
downPanel.add(down);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=0;
gridBagCon.gridy=4;
//gridBagCon.insets=new Insets(1,0,0,0);
gridBag.setConstraints(downprocess, gridBagCon);
downPanel.add(downprocess);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=2;
gridBagCon.gridy=4;
gridBagCon.insets=new Insets(1,0,0,0);
gridBag.setConstraints(downtime, gridBagCon);
downPanel.add(downtime);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=3;
gridBagCon.gridy=4;
gridBagCon.insets=new Insets(1,0,0,0);
gridBag.setConstraints(showspeed, gridBagCon);
downPanel.add(showspeed);
showstatus=new JTextField(35);
showstatus.setEditable(false);
gridBagCon=new GridBagConstraints();
gridBagCon.gridx=0;
gridBagCon.gridy=5;
gridBagCon.gridwidth=5;
gridBag.setConstraints(showstatus, gridBagCon);
downPanel.add(showstatus);
contentPane.add(messageScrollPane,BorderLayout.CENTER);
contentPane.add(downPanel,BorderLayout.SOUTH);
}
你贴了这么多代码:search=new JButton("搜索");
search.addActionListener(this); 可是你贴出来的代码,却不包含actionPerformed相关的逻辑,
呵呵,怎么查?
public void actionPerformed(ActionEvent e)
{
Object obj=e.getSource(); //获得事件类型
if(obj==setPort||obj==setport)
{
String inputValue = JOptionPane.showInputDialog("请输入端口号"); // sourceshow.setText(inputValue);
double i=Double.parseDouble(inputValue);
if((i>1&&i<1024)||i>65535){
JOptionPane.showMessageDialog(null, "端口应介于1024-65535", "端口错误", JOptionPane.ERROR_MESSAGE);
}
else
savePort=inputValue;
} //设置客户端端口并判断端口是否越界
else if(obj==connectServer||obj==connect)
{
if(savePort==null)
{
JOptionPane.showMessageDialog(null, "未设置端口", "连接服务器", JOptionPane.ERROR_MESSAGE);
}
//ConnectServer(); // 连接服务器
else
{
try{
socket=new Socket("127.0.0.1",4600);//注意两端的端口号必须一致
System.out.println("Connection!!");
os=new PrintWriter(socket.getOutputStream());// 由Socket对象得到输出流,发往服务器端的消息
} catch(Exception i){
System.out.print("not connect");
}
}
}//设置连接服务器
else if(obj==disconnect||obj==disConnect){
if(socket.isClosed()){
return;
}
try{
// os.close();
// is.close();
socket.close();
// message.append("与服务器断开连接");
System.out.println("disconnect");
}
catch(Exception j){
}
}//断开连接
else if(obj==search||obj==textsearch)
{
try{
String sea="1"; //设定标识符,“1”为搜索的内容
searchfilename=searchshow.getText();
messageToServer=sea+" "+searchfilename;
is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
os.println(messageToServer);
os.flush();
resultFromServer=is.readLine();
sourceshow.setText(resultFromServer);
}catch(Exception i){
System.out.println("search error");
}
}//搜索资源
else if(obj==upButton||obj==sharefileB){
try{
String clientIp=InetAddress.getLocalHost().getHostAddress(); //获取客户端的IP地址
is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String up="0"; //设定标识符,“0”为上传的内容
//获取 端口,文件名,文件路径
messageToServer =up+" "+clientIp;
System.out.println(messageToServer);
os.println(messageToServer); //向服务器发送消息
os.flush();
upresult=is.readLine();
sourceshow.setText(upresult);
}catch(Exception i){
System.out.print("upfile error");
}
}//上传文件
}
public static void main(String[] args) {
mainFrame mainframe=new mainFrame();
mainframe.setVisible(true);
mainframe.setResizable(false); //窗口不可伸缩
}}
代码好多啊。你的通信模型有点问题,
你的客户端是点击“链接”的时候建立到服务器的socket,
后续的查询、上传、下载都是使用该Socket,但你的serverThread这个类(作为一个服务线程)的run函数中,没有循环接收客户端的指令,
所以,客户端发送一次请求后,服务线程就退出了:public void run() {
try {
PrintWriter output = new PrintWriter(clientRequest.getOutputStream());
StringTokenizer tokenizer;
tokenizer = new StringTokenizer(test);
String sign = tokenizer.nextToken(); //不能用tokenizer.nextToken()直接去比较“0”,“1”。要先赋给一个变量,用该变量去比较,否则只能运行第一项
if (sign.equals("1"))
{
String searchcontent = tokenizer.nextToken();
System.out.println("search" + " " + searchcontent);
String result = "we find it";
output.println(result);
output.flush();
//搜索
}else if (sign.equals("0"))
{ output.println("上传成功");
output.flush();
}//equals 0 } catch (IOException e) {
System.out.println("server thread error");
}
//处理一次请求,该方法退出,也就意味着线程退出了,无法再接收更多的服务 }//run
改进方法有两个:
1、在这个服务线程的run方法中写一个while(true)循环,不断的接收客户端的请求,然后在客户端增加一个“断开”按钮,当发送断开指令时,服务线程用break退出该死循环
2、你的客户端改造成每次请求“先链接-发出请求-接收结果-断开链接”的模式,就像HTTP协议一样。