JAVA network

socket

Get connecting

Main methods:

1. Socket(host,port);  //Socket s=new Socket(host,port)
2. s.connect(new InetSocketAddress(host,port),timeout);
3. s.setSoTimeout(timeout);
4. s.isConnect()
5. s.isClosed()
6. s.getInputStream()
7. s.getOutputStream()

eg:

package socket;

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

public class Socke{
    public static void main(String[] args) throws IOException{
        String host="baidu.com";
        int po=80;
        Socket s=new Socket(host,po);
        s.setSoTimeout(10);
        /*
        Socket s=new Socket();
        s.connect(new InetSocketAddress(host,po),timeout);

         */
        System.out.println(s.isConnected());

        Scanner in =new Scanner(s.getInputStream(),"UTF-8");  //notice
        while(in.hasNextLine()){
            String line = in.nextLine();
            System.out.println(line);
        }
    }
}


Internet Address

1. InetAddress address1=InetAddress.getByName(String host)
2. InetAddress[] addresses=InetAddress.getAllByName(String host)
3. InetAddress address2=InetAddress.getLocalHost()
4. byte[] IP1=address1.getAddress()
5. String IP2=InetAddress.getHostAddress()

Get Internet Address from host names


package socket;
package InetAddress;

import java.io.*;
import java.net.*;  //include socket
import java.util.*;

public class Main{
    
    public static void main(String[] args) throws IOException{
        //get one address 
        InetAddress address=InetAddress.getByName("localhost");
        System.out.println(address);
        //get all address
        InetAddress[] addresses=InetAddress.getAllByName("baidu.com");
        for(int i=0;i<addresses.length;i++)
            System.out.println(addresses[i]);

        System.out.println();
        //get the address without name
        byte[] addressBytes=address.getAddress();
        for(int i=0;i<addressBytes.length;i++)
            System.out.print(addressBytes[i]+" ");

        System.out.println();
        //get the localhost ip
        InetAddress local_address=InetAddress.getLocalHost();
        System.out.println(local_address);
    }
}

Implemeting Servers

Serversocket

1. ServerSocket(port);  //ServerSocket S = new ServerSocket(port); 
2. s.accept();    		//return a Socket
3. s.close();
package Server;

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

public class Server_port{
    public static void main(String[] args)throws IOException{
        try(ServerSocket s=new ServerSocket(8189)){
            try(Socket incoming=s.accept()){   //the imcoming is a Socket
                InputStream istream=incoming.getInputStream();
                OutputStream outstream=incoming.getOutputStream();

                try(Scanner in = new Scanner(istream,"UTF-8")){
                    PrintWriter out=new PrintWriter(new OutputStreamWriter(outstream,"UTF-8"),true);
                    out.println("Hello world");

                    boolean done=false;
                    while(!done&&in.hasNextLine()){
                        String line=in.nextLine();
                        out.println("Echo"+line);
                        if(line.trim().equals("BYE")) done=true;
                    }
                }
            }
        }
    }
}

Servering Multiple Clinets

Use Tread to create a new thread

main code

            while(true){
                Socket incoming=s.accept();
                System.out.println("Spawning"+i);
                Runnable r = new XXX(incoming); //operate the requests
                Thread t = new Thread(r); //get new thread
                t.start();  //open thread
                i++;
            }
package threaded;

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


public class threaded{
    public static void main(String[] args){
        try(ServerSocket s=new ServerSocket(8189)){
            int i=1;

            while(true){
                Socket incoming=s.accept();
                System.out.println("Spawning"+i);
                Runnable r = new XXX(incoming);
                Thread t = new Thread(r); //get new thread
                t.start();  //open thread
                i++;
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    class XXX implements Runnable{
        private Socket incoming;

        public XXX(Socket incomingSocket){
            incoming=incomingSocket;
        }

        public void run(){
            try(InputStream inStream=incoming.getInputStream();OutputStream outStream = incoming.getOutputStream()){
                Scanner in = new Scanner(inStream,"UTF-8");
                PrintWriter out = new PrintWriter(new OutputStreamWriter(outStream,"UTF-8"),true);
                out.println("hello!Enter BYE to exit");

                boolean done=false;
                while(!done&&in.hasNextLine()){
                    String line=in.nextLine();
                    out.println("Echo: "+line);
                    if(line.trim().equals("BYE")) done=true;
                }
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

Half-close

1. s.shutdownOutput()
2. s.shutdownInput()
3. s.isOutputShutdown()
4. s.isInputShutdown()
package socket;

import java.net.*;  //include InetAddress
import java.io.*;
import java.util.*;

public class Sock{
    public static void main(String[] args) throws IOException {
        try(Socket socket = new Socket(host,port)){
            Scanner in = new Scanner(socket.getInputStream(),"UTF-8");
            PrintWriter writer=new PrintWriter(socket.getOutputStream());

            writer.print("xxx");
            writer.flush();
            socket.shutdownOutput();
            //half-closed
            //read response data
            while(in.hasNextLine()!=null){
                ....
            }

        }
    }
}

Get data from web

            URL url = new URL("http://www.baidu.com");
            
            //open an input stream for reading the resource data
            InputStream inStream=url.openStream();  
            Scanner in = new Scanner(inStream,"UTF-8");
            
			//manage the connection to the resource
            URLConnection connection=url.openConnection();
            connection.connect();  //get the connect
            InputStream is=connection.getInputStream();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值