佳礼资讯网

 找回密码
 注册

ADVERTISEMENT

查看: 955|回复: 4

java socket programming

[复制链接]
发表于 19-10-2008 09:38 PM | 显示全部楼层 |阅读模式
java, 我现在写着instant messenger的program,我只是做到chating,想问大家下,send file的问题
1)有什么example可以让我参考下吗??
2)我用着的是
   private void sendFile(String address)
   {
        try {
            FileOutputStream fos = new FileOutputStream(address);
            fileOutput = new ObjectOutputStream(fos);
            fileOutput.flush();
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
   }

   private void recFile(String address)
   {
        try {
            FileInputStream fis = new FileInputStream("/*address*/");
            ObjectInputStreamfile Input = new ObjectInputStream(fis);            
            fileOutput.read();
        }
       catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
   }

酱子对吗??

[ 本帖最后由 danny_vxe 于 19-10-2008 09:47 PM 编辑 ]
回复

使用道具 举报


ADVERTISEMENT

发表于 19-10-2008 09:51 PM | 显示全部楼层
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.net.*;
import java.io.*;

public class Chat extends JFrame implements ActionListener, Closeable{
       
        private String outData;
       
        private static String HOST;
        private static int PORT;
       
        private InData input = null;
        private PrintWriter pw = null;
        private Socket s = null;
        private ServerSocket ss = null;
       
        private JTextArea textArea= new JTextArea();
        private JTextField textData = new JTextField();
        private JButton buttonSend = new JButton ("Send");
        private JPanel panelFields = new JPanel (new GridLayout (1,2,5,5));
       
        public Chat (boolean isServer){
                super ("chat");
               
                getContentPane().add (new JScrollPane(textArea));
                getContentPane().add (panelFields, BorderLayout.SOUTH);
               
                panelFields.add(textData);
                panelFields.add(buttonSend);
               
                textArea.setEditable (false);
                textArea.setFocusable (false);
               
               
                setSize (500,300);
                setResizable(false);
                setVisible(true);
               
                try{
                        if (isServer){
                        textArea.append("[SYSTEM] Running as server\n");
                                ss = new ServerSocket (PORT);
                                s = ss.accept ();
                        }
                        else{
                        textArea.append("[SYSTEM] Running as client\n");
                                s = new Socket (HOST, PORT);
                        }
                        textArea.append ("[SYSTEM] Connected\n");
                       
                        input = new InData (textArea, s.getInputStream());
                        input.start ();
                        pw = new PrintWriter (s.getOutputStream());
                        textArea.append ("[SYSTEM] Connected\n");
                       
                        textArea.append ("[SYSTEM] Connected\n");
                        textData.addActionListener (this);
                        buttonSend.addActionListener (this);
                }
                catch (Exception ex){}
        }

        public void actionPerformed (ActionEvent evt){
                outData = textData.getText();
                textData.setText ("");
                textArea.append ("[ME] " +outData);
                textArea.append ("\n");
                textArea.setSelectionStart (textArea.getText().length());
               
                try{
                        pw.println ("[OTHER] " +outData);
                        pw.flush ();
                }
                catch (Exception ex){}
               
        }
       
        public void close(){
                try {
                        if (input != null)
                                input.close();
                        if (pw != null);
                                pw.close();
                        if (s!= null)
                                s.close();
                        if (ss!= null)
                                ss.close();
                }
                catch (Exception ex){}
        }
       
        public static void main (String args[]){
               
                if (args.length < 1 || args.length > 2){
                        System.out.println ("Usage:\n");
                        System.out.println ("To run as SERVER:");
                        System.out.println ("\tjava Chat <port>\n");
                        System.out.println ("To run as CLIENT:");
                        System.out.println ("\tjava Chat <port> <host/ip>");
                        return;
                }
               
                try{
                        PORT = Integer.parseInt (args[0]);
                        if (PORT < 1024 || PORT > 65535){
                                System.out.println ("Error: Port between 1024-65535");
                                return;
                        }
                }
                catch (Exception ex){
                        System.out.println ("Error: Port between 1024-65535");
                                return;
                }
               
                Chat obj = null;
               
                if (args.length == 1){
                        obj = new Chat(true);
                }
                else if (args.length == 2){
                        HOST = args[1];
                        obj = new Chat(false);
                }
               
                obj.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        }
}

class InData extends Thread implements Closeable{
        private String inData;
        private BufferedReader br = null;
        private JTextArea textArea = null;
       
        public InData(JTextArea ta, InputStream in){
                try {
                        textArea = ta;
                        br = new BufferedReader (new InputStreamReader(in));
                }
                catch (Exception ex){}
        }
       
        public void run(){
                textArea.append ("[SYSTEM] InData is ready\n");
                try{
                while ((inData = br.readLine()) != null){
                        textArea.append (inData);
                        textArea.append ("\n");
                }
                }
                catch (Exception ex){}
        }
       
        public void close () {
                try{
                        if (br != null)
                                br.close();
                               
                }
                catch (Exception ex){}
        }
}
回复

使用道具 举报

 楼主| 发表于 19-10-2008 10:00 PM | 显示全部楼层

回复 2# tatt2 的帖子

先谢谢了,给我一点时间看下..
回复

使用道具 举报

 楼主| 发表于 19-10-2008 10:34 PM | 显示全部楼层

回复 2# tatt2 的帖子

这个我做到了的,我需要的是send file的example
回复

使用道具 举报

发表于 21-10-2008 12:01 AM | 显示全部楼层
You can read the file contents into java.lang.Bytes using the java.io.FileInputStream. I assume that you know how to transfer java.io.serializable(google if you do not know) objects. Okay, now you got few approaches to send these bytes array to your target:

1. send these bytes by java.io.ObjectOutputStream method, writeByte(), one byte at each time, which is quite inefficient, but the simplest way.
2. create a class which implemented interface java.io.Serializable. Then in the class, contains a fixed size bytes array. You can then send this the file's content chunk by chunk of bytes array.
3. create a class which implemented interface java.io.Serializable. Then in the class, contains the full length of bytes, then you can send this object in one chunk.

For the 2nd and 3rd approach, you can freely add some fields containing information on the file to be sent, such as the file size, chunk_id(if send chunk by chunk)... etc.

Here's a sample code of serializable class for 3rd approach:
  1. public class WholeChunk
  2.         implements Serializable
  3. {
  4.     private final Byte[] b;
  5.    
  6.     public Users( Byte[] b )
  7.     {
  8.         this.b = b;
  9.     }
  10.    
  11.     public Byte[] getBytes()
  12.     {
  13.         return b;
  14.     }
  15.    
  16.     private void readObject( java.io.ObjectInputStream ois  )
  17.     throws ClassNotFoundException, java.io.IOException
  18.     {
  19.         ois.defaultReadObject();
  20.     }
  21.    
  22.     private void writeObject( java.io.ObjectOutputStream oos )
  23.     throws java.io.IOException
  24.     {
  25.         oos.defaultWriteObject();
  26.     }
  27. }
复制代码
Upon receiving the chunks of bytes, then use the FileOutputStream to write the bytes to the specified file. There goes it, a copy of the file is born...

[ 本帖最后由 solidx 于 22-10-2008 11:49 AM 编辑 ]
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

 

ADVERTISEMENT



ADVERTISEMENT



ADVERTISEMENT

ADVERTISEMENT


版权所有 © 1996-2023 Cari Internet Sdn Bhd (483575-W)|IPSERVERONE 提供云主机|广告刊登|关于我们|私隐权|免控|投诉|联络|脸书|佳礼资讯网

GMT+8, 23-12-2025 02:13 AM , Processed in 0.119261 second(s), 24 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表