关于Java网络编程的几个实例

来源:互联网 发布:淘宝母婴用品货源 编辑:程序博客网 时间:2024/06/07 00:45

1.使用UDP编程

   服务端:

  package net.csdn.udt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ThreadReceiver implements Runnable{

    /**
     * @param args
     */
    public static void main(String[] args) {
        new Thread(new ThreadReceiver()).start();
        
        Runnable r=new Runnable(){
            public void run() {
                try{
                    
                    DatagramSocket ds=new DatagramSocket();
                    
                    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                    
                    String line=null;
                    
                    while((line=br.readLine())!=null){
                        if(line.equals("ByeBye")){
                            System.out.println("Bye-Bye");
                            break;
                        }
                        byte[] buf=line.getBytes();
                        DatagramPacket dp=new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.49.234"),4455);
                        ds.send(dp);
                    }
                    ds.close();
                }catch(Exception e){
                    e.toString();
                }
                
                
            }
        };
        new Thread(r).start();
     
        Runnable r1=new Runnable(){
            public void run() {
                try{
                    
                    DatagramSocket ds=new DatagramSocket();
                    
                    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                    
                    String line=null;
                    
                    while((line=br.readLine())!=null){
                        if(line.equals("ByeBye")){
                            System.out.println("Bye-Bye");
                            break;
                        }
                        byte[] buf=line.getBytes();
                        DatagramPacket dp=new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.49.234"),9008);
                        ds.send(dp);
                    }
                    ds.close();
                }catch(Exception e){
                    e.toString();
                }
                
                
            }
        };
        new Thread(r1).start();
        
        Runnable r2 =new Runnable(){

            @Override
            public void run() {
                try{
                    
                    DatagramSocket ds=new DatagramSocket();
                    
                    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                    
                    String line=null;
                    
                    while((line=br.readLine())!=null){
                        if(line.equals("ByeBye")){
                            System.out.println("Bye-Bye");
                            break;
                        }
                        byte[] buf=line.getBytes();
                        DatagramPacket dp=new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.49.13"),9008);
                        ds.send(dp);
                    }
                    ds.close();
                }catch(Exception e){
                    e.toString();
                }
                
                
            }
            
        };
        new Thread(r2).start();

public void run() {
        try{
            
            DatagramSocket ds=new DatagramSocket(9008);
            
            while(true){
                byte[] buf=new byte[1024];
                
                DatagramPacket dp=new DatagramPacket(buf,buf.length);
                
                ds.receive(dp);
                
                String ip=dp.getAddress().getHostAddress();
                String data=new String(dp.getData(),0,dp.getLength());
                System.out.println(ip+":"+data);
            }
            //ds.close();
            
        
        }catch(Exception e){
            e.toString();
        }
        
    }
}


客户端:


package net.csdn.udt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ThreadSender implements Runnable{

    /**
     * @param args
     */
    public static void main(String[] args) {
        new Thread(new ThreadSender()).start();
 
}

    @Override
    public void run() {
        try{
            
            DatagramSocket ds=new DatagramSocket();
            
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            
            String line=null;
            
            while((line=br.readLine())!=null){
                if(line.equals("ByeBye")){
                    System.out.println("Bye-Bye");
                    break;
                }
                byte[] buf=line.getBytes();
                DatagramPacket dp=new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.49.13"),4455);
                ds.send(dp);
            }
            ds.close();
        }catch(Exception e){
            e.toString();
        }
        
        
    }

}


2.使用TCP协议编程


服务端:

/*客户端通过键盘录入信息,发送到服务器端
服务器端收到信息后,将信息转为大写返回给客户端。*/



package net.csdn.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer2 {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        ServerSocket ss=new ServerSocket(9009);
        
        Socket s=ss.accept();
        
        System.out.println(s.getInetAddress().getHostAddress()+"...connection");
        //读取客户的信息的输入流
        InputStream in=s.getInputStream();
        
        BufferedReader brin=new BufferedReader(new InputStreamReader(in));
        //向客户端发送信息输出流
        BufferedWriter brout=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        
        String line=null;
        
        while((line=brin.readLine())!=null){
            System.out.println("client:"+line);
            
            brout.write(line.toUpperCase());
            brout.newLine();
            brout.flush();
            
        }
        s.close();
        ss.close();

    }

}

客户端:

package net.csdn.socket;

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

public class TcpClient2 {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        
        Socket s=new Socket("192.168.49.13",9009);
        //获取键盘录入
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        //数据输出给服务器端
        OutputStream out=s.getOutputStream();
        
        BufferedWriter bwout=new BufferedWriter(new OutputStreamWriter(out));
        //获取服务器端返回的数据
        BufferedReader brin=new BufferedReader(new InputStreamReader(s.getInputStream()));
        
        String line=null;
        
        while((line=br.readLine())!=null){
            if(line.equals("over"))
                break;
            
            bwout.write(line);
            bwout.newLine();
            bwout.flush();
            
            String str=brin.readLine();
            System.out.println("server:"+str);
            
            
        }
        br.close();
        s.close();

    }

}

3.使用TCP协议编写程序实现从客户端上传文本到服务端

服务端:

package net.csdn.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class UpdownLoadTextServer {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        ServerSocket ss =new ServerSocket();
        Socket s =ss.accept();
         System.out.println(s.getInetAddress().getHostAddress()+"is connecting...");
        BufferedReader br =new BufferedReader(new InputStreamReader(s.getInputStream()));
        PrintWriter pw =new PrintWriter("E:\\");
        String line =null;
        while((line=br.readLine())!=null){
            
        }
    }

}

客户端:

package net.csdn.tcp;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class UpdownLoadTextClient {

    /**
     * @param args
     * @throws IOException
     * @throws UnknownHostException
     */
    public static void main(String[] args) throws UnknownHostException, IOException {
        Socket s =new Socket(InetAddress.getByName("192.168.49.13"), 1234);
        BufferedReader br =new BufferedReader(new FileReader("D:\\c.sql"));
        PrintWriter pw =new PrintWriter(s.getOutputStream());
        String len =null;
        while((len=br.readLine())!=null){
            pw.println(len);
        }
        s.shutdownOutput();
        
        InputStream inStream =s.getInputStream();
        byte [] buf =new byte[1024];
        int line =0;
        while((line=inStream.read(buf, 0, buf.length))!=-1){
          System.out.println(new String(buf));    
        }
        

    }

}

4.使用TCP协议实现从客户端上传图片到服务端

服务端:

package net.csdn.tcp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class UpdownLoadImageServer implements Runnable {
    private Socket s;
    public UpdownLoadImageServer(Socket s){
         // new Thread(new UpdownLoadImageServer());
        this.s=s;
          
          
          
      }

    public static void main(String[] args) throws IOException {
        
    ServerSocket ss=new ServerSocket(1111);
    
//    Socket s=ss.accept();在外面写会怎么样?
    while(true){
        Socket s=ss.accept();
        new Thread(new UpdownLoadImageServer(s)).start();
    
    }
    
    
    
    }

    @Override
    public void run() {
        try {
            int count =1;
            System.out.println(s.getInetAddress().getHostAddress()+"is connecting...");
            String ip =s.getInetAddress().getHostName();
            InputStream is =s.getInputStream();
            File fd =new File("E:\\pic");
            File fp=new File(fd,ip+"time"+count+".jpg");
            if(fp.exists())
                fp=new File(fd,ip+"time"+(count++)+".jpg");
            FileOutputStream fos =new FileOutputStream(fp);
            byte image[] =new byte[1024];
            
            int len=0;
//            int len=is.read(image);
            //while(len!=-1){
            while((len=is.read(image))!=-1){
                //System.out.println(s.getInetAddress().getHostAddress()+"is connecting...");
                 fos.write(image, 0, len);
                // fos.flush();//
            }
            
            OutputStream os=s.getOutputStream();
            os.write("<font color ='red' >上传成功!</font>".getBytes());
         //   os.flush();
            
            fos.close();
            s.close();
        } catch (Exception e) {
            e.toString();
        }
        
    }
}

客户端:

package net.csdn.tcp;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class UpdownLoadImageClient {

    /**
     * @param args
     * @throws IOException
     * @throws UnknownHostException
     */
    public static void main(String[] args) throws UnknownHostException, IOException {
        Socket s = new Socket("192.168.49.13",1111);
        //s.getInputStream();
        if(args.length==0){
        System.err.println("请指定一个合法的图片文件");  
        return;
        }
        if(args[0].endsWith(".wmf")||args[0].endsWith(".jpg")||args[0].endsWith(".jpeg")||args[0].endsWith(".gif")||args[0].endsWith("ai")||args[0].endsWith("pdg"))
        {
              File fd=new File(args[0]);
               // File f =new File(fd);
              FileInputStream fis =new FileInputStream(fd);
             OutputStream os = s.getOutputStream();
              byte [] image =new byte[1024];
//             int len =fis.read(image);//如果这样写到了while循环里就只会执行一次了,所以看到的只是部分图片
            int len =0;
            while((len=fis.read(image))!=-1){
//              while((len!=-1){
                  os.write(image, 0, len);
                  
                  //os.flush();//
                  
              }
            s.shutdownOutput();
              
              
             InputStream is = s.getInputStream();
              byte [] re =new byte[1024];
              len =is.read(re);//这里怎么可以这样用?
//              int i =is.read(re);
            
              System.out.println(new String(re,0,len));
              fis.close();
              s.close();
        }else{
            System.err.println("非法的图片文件输入!");
        }
         
      
    
       
    }

}

5.使用无套接字的Socket()实现客户端与服务端的连接

客户端:

package net.csdn.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class NoParagramSocket {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        Socket s =new Socket();
        String url ="192.168.49.13";
        int port =4442;
        SocketAddress socketAddress =new InetSocketAddress(url, port);
        //s.connect(socketAddress,3);//可以设置连接超时
        s.connect(socketAddress);//未设置连接超时
        s.close();

    }

}

服务端:

package net.csdn.socket;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ServiceSocketer {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
    ServerSocket ss =new ServerSocket(4442);
    Socket s =ss.accept();
    System.out.println(s.getInetAddress().getHostAddress()+"is connecting...");
    InputStream inSteram =s.getInputStream();
    BufferedReader br =new BufferedReader(new InputStreamReader(inSteram));
 
    
    
    OutputStream outStream =s.getOutputStream();
    BufferedWriter bw =new BufferedWriter(new OutputStreamWriter(outStream));
    String line =null;
    while((line=br.readLine())!=null){
        System.out.println(s.getInetAddress().getHostAddress()+"发送请求:");
        System.out.println(line);
       
//        bw.write(line.toUpperCase());
        bw.write("收到");
        bw.newLine();
        bw.flush();
       
    }

    
   br.close();
   s.close();
    }
   
    }


6.关于URL类的使用

package net.csdn.socket;

import java.net.MalformedURLException;
import java.net.URL;

public class URLIntroduce {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String url ="http://www.csdn.net/csss/css.html?name = css";
        URL ur =new URL(url);
        String file =ur.getFile();
        String path =ur.getPath();
        int port =ur.getPort();
        String host =ur.getHost();
        String protocol =ur.getProtocol();
        String query =ur.getQuery();
        System.out.println("file:"+file);
        System.out.println("path:"+path);
        System.out.println("port:"+port);
        System.out.println("host:"+host);
        System.out.println("protocol:"+protocol);
        System.out.println("query:"+query);

    }

}

7.关于数据的转码、与加码

package net.csdn.socket;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class URLEDCoder {

    /**
     * @param args
     * @throws UnsupportedEncodingException
     */
    public static void main(String[] args) throws UnsupportedEncodingException {
        String code =new String("站在峰顶看日落");
        String ec =URLEncoder.encode(code, "utf-8");
        System.out.println(ec);
       System.out.println("____________");
        String ecode =new String("%E7%AB%99%E5%9C%A8%E5%B3%B0%E9%A1%B6%E7%9C%8B%E6%97%A5%E8%90%BD");
        String dcode =URLDecoder.decode(ecode, "utf-8");
        System.out.println(dcode);
    }

}




原创粉丝点击