标题:关于客户端与服务器端连接的问题(图形界面)
取消只看楼主
windyfzz
Rank: 2
等 级:禁止访问
帖 子:90
专家分:12
注 册:2010-7-25
结帖率:68%
 问题点数:0 回复次数:0 
关于客户端与服务器端连接的问题(图形界面)
服务器端:

import *;
import *;

import javax.swing.*;
import *;
import java.awt.*;

import java.awt.event.*;

    public class CreateServer extends JFrame implements Runnable
    {
        
        JTextField jtfName;  //名字输入域
        
        JTextArea jtaChat;  //显示聊天信息
        JTextArea jtaInput;  //输入消息
        JButton jbSend;
        
        int sportNum=6000;
        ServerSocket ss;
        Socket s;
        OutputStream os;
        InputStream is;
        byte[] buf=new byte[10*1024];
        int len=0;
        
    CreateServer()
    {
        
         super("服务器端");  //调用父类构造函数
         

        
         setLocation(300,300);
           setSize(400,300);  //设置窗口尺寸
           setVisible(true);  //设置窗口可视
           setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
         
        Container container=this.getContentPane();  //得到容器
        JPanel p=new JPanel();  //初始化一个面板
        jtfName=new JTextField(10);  //初始化名字输入域   
        
        JButton linkToClient=new JButton("连接客户端");
        JButton disconnect=new JButton("断开连接");
        
        
        linkToClient.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
               
                  jtaChat.append("正在等待客户端的连接...");    ///////////  疑问一
                  jtaChat.append("\n");
                  
                try
                 {
               
                  ss=new ServerSocket(sportNum);
                  s=ss.accept();
                  os=s.getOutputStream();
                  is=s.getInputStream();
                  {
                      //jtaChat.setText("");
                  }
                  /*if((is=s.getInputStream())!=null)
                  {
                      //jtaChat.setText("");
                  }*/
                  
                     
                  
                  
                 }
                 catch(Exception ex)
                 {
                     ex.printStackTrace();
                 }
               
            }
            
        });
        
        
        disconnect.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                jtaChat.append("与客户端的连接已断开!");
                jtaChat.append("\n");
               
                try
                {
                    os.close();
                    is.close();
                    ss.close();
                    s.close();
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
            
        });
        
        p.add(new JLabel("昵称:"));  //增加昵称标签
        p.add(jtfName);  //增加名字输入域
        p.add(linkToClient);
        p.add(disconnect);
   
      
        container.add(p,BorderLayout.NORTH);  //在容器上增加面板
     
        jtaChat=new JTextArea();  //初始化信息显示文本框
        jtaChat.setLineWrap(true);
      
         container.add(new JScrollPane(jtaChat,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
         ,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
             ),BorderLayout.CENTER);  //在容器上增加信息显示文本框

        Box box=new Box(BoxLayout.X_AXIS);  //初始化一个Box
        jtaInput=new JTextArea(3,20);  //初始化消息输入域
        jtaInput.setLineWrap(true);
        jbSend=new JButton();  //初始化发送按钮
        jbSend.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
               
                replaceMessage();
                jtaInput.setText("");
            }
            
        });
        
        jbSend.setText("发送");
        
        
        box.add(new JScrollPane(jtaInput,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
                 ,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ));  //增加消息输入域
        
        box.add(jbSend);
        
        container.add(box,BorderLayout.SOUTH);  //在容器上增加box
        
        
         Action sendMessage = new AbstractAction()
           {  //发送消息Action
               public void actionPerformed(ActionEvent e)
               {
                  
                   replaceMessage();  //更新消息显示框
                   jtaInput.setText("");
            }
           };
            
            jtaInput.getInputMap().put(KeyStroke.getKeyStroke("ENTER"),"send");  //键盘事件处理,按受回车事件
            jtaInput.getActionMap().put("send",sendMessage);  //回车时的处理(调用发送消息Action)
    }
   
    private void replaceMessage()
    {
        try
        {
            jtaChat.append(jtfName.getText()+"说: ");
            //jtaChat.append("\n");
            jtaChat.append(jtaInput.getText());
            jtaChat.append("\n");
            
            os.write((jtfName.getText()+"说: "+jtaInput.getText()).getBytes());
            
            
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
    }
   
    public void run()
    {
        
        String str;
        while(true)
        {
            try
            {
                len=is.read(buf);
                str=new String(buf,0,len);
                jtaChat.append(str);
                jtaChat.append("\n");
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
   
   
    public static void main(String[] args)

    {
        CreateServer cs=new CreateServer();
        new Thread(cs).start();
    }
     
   
}






客户端:

import *;
import *;

import javax.swing.*;

import *;
import java.awt.*;

import java.awt.event.*;

    public class CreateClient extends JFrame implements Runnable
    {
        
        JTextField jtfName;  //名字输入域
        JTextField ipName;   //IP输入
        JTextArea jtaChat;  //显示聊天信息
        JTextArea jtaInput;  //输入消息
        JButton jbSend;
        
        int sportNum=6000;
        
        Socket s;
        OutputStream os;
        InputStream is;
        byte[] buf=new byte[10*1024];
        int len=0;
        
    CreateClient()
    {
        
         super("客户端");  //调用父类构造函数
         
        
        
         setLocation(300,300);
           setSize(520,300);  //设置窗口尺寸
           setVisible(true);  //设置窗口可视
           setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //关闭窗口时退出程序
         
        Container container=this.getContentPane();  //得到容器
        JPanel p=new JPanel();  //初始化一个面板
        jtfName=new JTextField(5);  //初始化名字输入域   
        ipName=new JTextField(8);
        
        JButton linkToServer=new JButton("连接服务器端");
        JButton disconnect=new JButton("断开连接");
        
        linkToServer.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                String ipstr=ipName.getText().trim();
                try
                 {
                    if(ipstr.length()==0)
                    {
                        s=new Socket(InetAddress.getByName(null),sportNum);//如果想在一台机子上做连接,就不输入ip
                    }
                    
                    else
                        s=new Socket(InetAddress.getByName(ipstr),sportNum);
                  
                    os=s.getOutputStream();
                    is=s.getInputStream();
               
                 }
                 catch(Exception ex)
                 {
                     ex.printStackTrace();
                 }
               
            }
            
        });
        
        disconnect.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                jtaChat.append("与服务器端的连接已断开!");
                jtaChat.append("\n");
               
                try
                {
                    os.close();
                    is.close();
                  
                    s.close();
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
            
        });
        
        p.add(new JLabel("昵称:"));  //增加昵称标签
        p.add(jtfName);  //增加名字输入域
        p.add(new JLabel("输入服务器端IP:"));
        p.add(ipName);
        p.add(linkToServer);
        p.add(disconnect);
   
      
        container.add(p,BorderLayout.NORTH);  //在容器上增加面板
     
        jtaChat=new JTextArea();  //初始化信息显示文本框
        jtaChat.setLineWrap(true);
      
         container.add(new JScrollPane(jtaChat,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
         ,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
             ),BorderLayout.CENTER);  //在容器上增加信息显示文本框

        Box box=new Box(BoxLayout.X_AXIS);  //初始化一个Box
        jtaInput=new JTextArea(3,20);  //初始化消息输入域
        jtaInput.setLineWrap(true);
        jbSend=new JButton();  //初始化发送按钮
        jbSend.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
               
                replaceMessage();
                jtaInput.setText("");
               
            }
            
        });
        
        jbSend.setText("发送");
        
        
        box.add(new JScrollPane(jtaInput,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
                 ,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ));  //增加消息输入域
        
        box.add(jbSend);
        
        container.add(box,BorderLayout.SOUTH);  //在容器上增加box
        
        
         Action sendMessage = new AbstractAction()
           {  //发送消息Action
               public void actionPerformed(ActionEvent e)
               {
                  
                   replaceMessage();  //更新消息显示框
                   jtaInput.setText("");
            }
           };
            
            jtaInput.getInputMap().put(KeyStroke.getKeyStroke("ENTER"),"send");  //键盘事件处理,按受回车事件
            jtaInput.getActionMap().put("send",sendMessage);  //回车时的处理(调用发送消息Action)
    }
   
    private void replaceMessage()
    {
        try
        {
            jtaChat.append(jtfName.getText()+"说: ");
            //jtaChat.append("\n");
            jtaChat.append(jtaInput.getText());
            jtaChat.append("\n");
            
            os.write((jtfName.getText()+"说: "+jtaInput.getText()).getBytes());
            jtaInput.setText("");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
    }
   
    public void run()
    {
        
        String str;
        while(true)
        {
            try
            {
                len=is.read(buf);
                str=new String(buf,0,len);
                jtaChat.append(str);
                jtaChat.append("\n");
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
   
   
    public static void main(String[] args)

    {
        CreateClient cc=new CreateClient();
        new Thread(cc).start();
    }
     
   
}


疑问一:
 jtaChat.append("正在等待客户端的连接...");我的意思是说开启服务器端,然后点击 连接客户端 ,这时应该在聊天显示内容的文本域中显示
"正在等待客户端的连接..."
可是问题是只有当点击客户端的 连接服务器端 按钮时,在客户端与服务器端建立连接以后才显示这段文字。这是为什么啊?

疑问二:
  如何在一方断开连接以后,在另一方显示一方已断开连接。 比如当点击服务器端的 断开连接 是,会立即在客户端的聊天显示内容的文本域中显示客户端断开连接的消息。这又怎么实现?

疑问三:
我用两台机子做实验,我自己的机子开启服务器端,同学的机子开启客户端,然后他在客户端的ip输入中输入我的ip,我们想建立连接,为什么连接建立不了啊,点击程序也没有任何反应,程序好像死掉了。这又是为什么啊,怎么解决啊(我们之间已经建立网络连接)?  详细的话请看代码,麻烦有经验的高手帮忙,谢了啊!
搜索更多相关主题的帖子: Socket 服务器 客户端 名字 聊天 
2011-03-22 10:43



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-334388-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.642163 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved