用网络编程和多线程来实现 具体代码怎么写啊?现在有一些零碎的代码在脑子里,就是没有逻辑,不知道如何组织,哪位大侠贴下完整的代码吧

解决方案 »

  1.   

    Server:/*
     * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     *   - Redistributions of source code must retain the above copyright
     *     notice, this list of conditions and the following disclaimer.
     *
     *   - Redistributions in binary form must reproduce the above copyright
     *     notice, this list of conditions and the following disclaimer in the
     *     documentation and/or other materials provided with the distribution.
     *
     *   - Neither the name of Sun Microsystems nor the names of its
     *     contributors may be used to endorse or promote products derived
     *     from this software without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
     * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
     * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
     * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
     * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
     * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */ import java.net.*;
    import java.io.*;public class SockServer {
        public static void main(String[] args) throws IOException {        ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(9876);
            } catch (IOException e) {
                System.err.println("Could not listen on port: 9876.");
                System.exit(1);
            }        Socket clientSocket = null;
            try {
                clientSocket = serverSocket.accept();
            } catch (IOException e) {
                System.err.println("Accept failed.");
                System.exit(1);
            }        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(
    new InputStreamReader(
    clientSocket.getInputStream()));
            String inputLine, outputLine;
            SockProcesser kkp = new SockProcesser();        outputLine = kkp.processInput(null);
            out.println(outputLine);        while ((inputLine = in.readLine()) != null) {
                 outputLine = kkp.processInput(inputLine);
                 out.println(outputLine);
                 if (outputLine.equals("Bye."))
                    break;
            }
            out.close();
            in.close();
            clientSocket.close();
            serverSocket.close();
        }
    }
    class SockProcesser {
        private static final int WAITING = 0;
        private static final int SENTKNOCKKNOCK = 1;
        private static final int SENTCLUE = 2;
        private static final int ANOTHER = 3;    private static final int NUMJOKES = 5;    private int state = WAITING;
        
        public String processInput(String theInput) {
            return "I am server, you said:"+theInput;
        }
    }
      

  2.   

    client
    /*
     * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     *   - Redistributions of source code must retain the above copyright
     *     notice, this list of conditions and the following disclaimer.
     *
     *   - Redistributions in binary form must reproduce the above copyright
     *     notice, this list of conditions and the following disclaimer in the
     *     documentation and/or other materials provided with the distribution.
     *
     *   - Neither the name of Sun Microsystems nor the names of its
     *     contributors may be used to endorse or promote products derived
     *     from this software without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
     * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
     * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
     * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
     * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
     * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */ import java.io.*;
    import java.net.*;public class EchoClient {
        public static void main(String[] args) throws IOException {        Socket echoSocket = null;
            PrintWriter out = null;
            BufferedReader in = null;        try {
                echoSocket = new Socket("localhost", 9876);
                out = new PrintWriter(echoSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(
                                            echoSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for "
                                   + "the connection to: localhost.");
                System.exit(1);
            } BufferedReader stdIn = new BufferedReader(
                                       new InputStreamReader(System.in));
    String userInput;
    System.out.println("请输入信息:");
    while ((userInput = stdIn.readLine()) != null) {
        out.println(userInput);
        System.out.println("server: " + in.readLine());
    } out.close();
    in.close();
    stdIn.close();
    echoSocket.close();
        }
    }
      

  3.   

    大一时候的没事时做的,比较简单,同时开两个,先登陆的那个就是做服务器希望对你有用package chatSystemPak;import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;public class ChatSystem extends JFrame{  JPanel mainPanel;
      JPanel panel1,panel2,panel3;
      JLabel yourName,myName;
      JButton btnSend;
      JTextArea textAreal;
      JTextArea textArea2;
      JScrollPane scrollPane1;
      JScrollPane inputScrollPane;
      JButton btnConnect,btnSave,btnClose;  String myNickname,yourNickname;
      boolean chgFlag;
      public boolean hasClient;
      public boolean hasServer;  ServerThread srvThread;                        //定义两个线程
      ClientThread cltThread;  ChatSystem()                                   //构造函数
      {
        textAreal = new JTextArea();
        textArea2 = new JTextArea();
      }  public static void main(String argv[])         //主函数
      {
        final ChatSystem frame = new ChatSystem();
        frame.setTitle("聊天系统");
        try
        {
          UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
        }
        catch(Exception e1)
        {
          e1.printStackTrace();
        }
        frame.myNickname = JOptionPane.showInputDialog(frame,"请输入你昵称:","");
        if((frame.myNickname == null)||(frame.myNickname.equals("")))
        {
          System.exit(0);
        }
        frame.chgFlag = false;
        frame.setDefaultCloseOperation(frame.DO_NOTHING_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter(){
          public void windowClosing(WindowEvent e2)
          {
            frame.confirmClose();
          }
        });    frame.addComponent();
        frame.pack();
        frame.setVisible(true);
        frame.hasServer = false;
        frame.hasClient = false;
        frame.srvThread = new ServerThread("ServerThread",frame);
        frame.srvThread.start();
      }                                             //主函数结束的地方public void addComponent()
    {
      mainPanel = new JPanel();
      mainPanel.setLayout(new BoxLayout(mainPanel,BoxLayout.PAGE_AXIS));
      getContentPane().add(mainPanel);
      panel1 = new JPanel();
      panel2 = new JPanel();
      panel3 = new JPanel();  yourName = new JLabel("对方的昵称: ");
      myName = new JLabel("我的昵称: " +myNickname);
      panel1.setLayout(new GridLayout(0,2));
      panel1.add(yourName);
      panel1.add(myName);  textArea2 = new JTextArea(6,40);
      textArea2.setEditable(true);
      textArea2.setFont(new Font("隶书",Font.BOLD,20));
      textArea2.setCaretColor(Color.BLUE);
      textArea2.setForeground(Color.ORANGE);
      textArea2.setLineWrap(true);
      textArea2.setWrapStyleWord(true);
      inputScrollPane = new JScrollPane(textArea2,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);  btnSend = new JButton("发送");
      btnSend.addActionListener(new ChatActionListenerClass(this));
      btnSend.setActionCommand("发送");  textAreal = new JTextArea(6,40);
      textAreal.setEditable(false);
      textAreal.setLineWrap(true);
      textAreal.setFont(new Font("隶书",Font.BOLD,20));
      textAreal.setForeground(Color.orange);
      textAreal.setWrapStyleWord(true);
      scrollPane1 = new JScrollPane(textAreal,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);  btnConnect = new JButton("连接");
      btnSave = new JButton("保存");
      btnClose = new JButton("关闭");  btnConnect.addActionListener(new ChatActionListenerClass(this));
      btnSave.addActionListener(new ChatActionListenerClass(this));
      btnClose.addActionListener(new ChatActionListenerClass(this));
      btnConnect.setActionCommand("连接");
      btnSave.setActionCommand("保存");
      btnClose.setActionCommand("关闭");  panel3 = new JPanel();
      panel3.setLayout(new FlowLayout(FlowLayout.CENTER,15,5));  panel3.add(btnConnect);
      panel3.add(btnSave);
      panel3.add(btnClose);
      panel3.add(btnSend);  inputScrollPane.setBorder(BorderFactory.createEtchedBorder(Color.BLACK,Color.BLACK));
      scrollPane1.setBorder(BorderFactory.createEtchedBorder(Color.black,Color.black));  mainPanel.add(panel1);
      mainPanel.add(scrollPane1);
      mainPanel.add(Box.createRigidArea(new Dimension(15,15)));
      mainPanel.add(inputScrollPane);
      mainPanel.add(panel3);
    }void confirmClose()                            //弹出询问是否要保存聊天记录的对话框
    {
      if(chgFlag)
      {
        int returnValue = JOptionPane.showConfirmDialog(null,"聊天记录还未保存,是否保存?","保存记录",JOptionPane.YES_NO_CANCEL_OPTION);
        if(returnValue == JOptionPane.YES_OPTION)
        {
          boolean saveFlag = saveFile();
          if(saveFlag)
          {
            System.exit(0);
          }
        }
        else if(returnValue == JOptionPane.NO_OPTION)
        {
          System.exit(0);
        }
      }
      else
      {
        System.exit(0);
      }}boolean saveFile()   //保存聊天记录的函数
    {
      JFileChooser fc = new JFileChooser();
      fc.setDialogType(JFileChooser.SAVE_DIALOG);
      int rtnValue = fc.showOpenDialog(this);
      if(rtnValue == JFileChooser.APPROVE_OPTION)
      {
        try
        {
          File file1 = fc.getSelectedFile();
          FileWriter writer1 = new FileWriter(file1);
          writer1.write(textAreal.getText());
          writer1.close();
          return true;
        }
        catch(IOException ioe)
        {
          return false;
        }  }
      else
      {
        return false;
      }
    }
      

  4.   

    接上面  public void chatActionPerformed(ActionEvent e)           //事件监听类的具体实现
      {
        if(("输入文字".equals(e.getActionCommand()))||("发送".equals(e.getActionCommand())))
        {
          String strText = textArea2.getText();
          addText(myNickname, strText);
          sendMessage(strText);
        }
        else if("连接".equals(e.getActionCommand()))
        {
          cltThread = new ClientThread("ClientThread",this);
          cltThread.start();
        }
        else if("保存".equals(e.getActionCommand()))
        {
          boolean saveFlag = saveFile();
          if(saveFlag)
          {
            chgFlag = false;
          }
        }
        else if("关闭".equals(e.getActionCommand()))
        {
          confirmClose();
        }
      }  void addText(String nickname,String strText)
      {
        java.util.Date d = new java.util.Date();
        textAreal.append("  "+nickname+":  "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+"\n  "+strText+"\r\n");
        textArea2.replaceRange("",0,textArea2.getSelectionEnd());
        chgFlag = true;
        //text1.selectAll();
        textAreal.setCaretPosition(textAreal.getDocument().getLength());
      }  public void sendMessage(String msg)
      {
        Socket sender;
        if(hasClient)
        {
          sender = cltThread.cltSocket;
        }
        else
        {
          sender = srvThread.connSocket;
        }
        if(sender == null)
        {
          return;
        }
        try
        {
          PrintWriter out = new PrintWriter(sender.getOutputStream(),true);
          out.println(msg);    }
        catch(IOException ioe)
        {
          ioe.printStackTrace();
        }
      }}                                                    //主类结束的地方
    class ChatActionListenerClass implements ActionListener    //事件监听类
    {
      ChatSystem frame;  ChatActionListenerClass(ChatSystem frame)
      {
        this.frame = frame;
      }  public void actionPerformed(ActionEvent e)
      {
        frame.chatActionPerformed(e);
      }
    }class ServerThread extends Thread
    {
      ServerSocket srvSocket;
      Socket connSocket;
      ChatSystem frame;  public ServerThread(String str,ChatSystem frame)    //服务器类
      {
        super(str);
        this.frame = frame;
      }  public void run()
      {
        try
        {
        srvSocket= new ServerSocket(5555);
        while(!frame.hasClient && !frame.hasServer)
        {
          connSocket = srvSocket.accept();
          frame.hasServer = true;
        }
        }
        catch(Exception ste)
        {
          ste.printStackTrace();
        }    if(frame.hasClient)
        {
          try
          {
            srvSocket.close();        if (connSocket != null)
            {
              connSocket.close();
            }
          }
          catch(IOException ioe)
          {
            ioe.printStackTrace();
          }
        }
        else
        {
          try
          {
            BufferedReader in = new BufferedReader(new InputStreamReader(connSocket.getInputStream()));
            String inStr;
            frame.yourNickname = in.readLine();
            frame.yourName.setText("对方的昵称:" + frame.yourNickname);
            frame.sendMessage(frame.myNickname);
            while ( (inStr = in.readLine()) != null)
            {
              frame.addText(frame.yourNickname, inStr);
            }
            in.close();
            connSocket.close();
            srvSocket.close();
          }
          catch(IOException ioe)
          {
            ioe.printStackTrace();
          }
        }
      }
    }class ClientThread extends Thread                       //客户端类
    {
      ChatSystem frame;
      Socket cltSocket;  public ClientThread(String str,ChatSystem frame)
      {
        super(str);
        this.frame = frame;
      }  public void run()
      {
        String hostName;
        hostName = JOptionPane.showInputDialog(frame,"请输入对方电脑的IP地址: ","");
        if((hostName == null) || (hostName.equals("")))
        {
          return;
        }    try
        {
          cltSocket = new Socket(hostName, 5555);
        }
        catch(IOException ioe)
        {
          ioe.printStackTrace();
          JOptionPane.showMessageDialog(frame,"无法到对方的电脑");
          return;
        }
        frame.hasClient =true;
        frame.sendMessage(frame.myNickname);
        try
        {
          BufferedReader in = new BufferedReader(new InputStreamReader(cltSocket.
              getInputStream()));      String instr;
          instr = in.readLine();
          frame.yourNickname = instr;
          frame.yourName.setText("对方的昵称: "+instr);
          while((instr = in.readLine()) != null)
          {
            frame.addText(frame.yourNickname,instr);
          }
          in.close();
          cltSocket.close();
        }
        catch(IOException ioe)
        {
          ioe.printStackTrace();
        }
      }
    }