阿猛学习笔记java十五网络通信

二十网络通信

java.net.*包中

1.InetAddress

表示ip地址

常用方法

static InetAddress getByName(String host) 通过主机名称得到InetAddress对象

static InetAddress getLocalHost() 得到本机的InetAddress对象

String getHostName() 得到主机域名

String hostAddress() 得到主机ip地址

boolean isReachable(int timeout) 判断地址是否可达且指定超时时间

public class S1InetAddress {
	public static void main(String[] args) throws IOException {
		InetAddress ia=InetAddress.getByName("www.baidu.com");
		String hostName=ia.getHostName();
		String hostAddress=ia.getHostAddress();
		System.out.println("百度的地址为:"+hostName+"\t"+hostAddress);
		InetAddress ial=InetAddress.getLocalHost();
		String hostNamel=ial.getHostName();
		String hostAddressl=ial.getHostAddress();
		System.out.println("本机地址为:"+hostNamel+"\t"+hostAddressl);
		boolean f=ial.isReachable(1000);
		System.out.println("本机是否可达:"+f);
	}
}
2.URL

统一资源定位符

构造方法

public URL(String spec)根据指定的地址实例化 URL 对象
public URL(String protocol,String host,int port,String file) 实例化 URL 对象,并指定协议、主机、端口名称、资源文件

常用方法

public URLConnectionopenConnection()取得一个 URLConnection 对象
public final InputStream openStream() 取得输入流

public class S2URL {
	public static void main(String[] args) throws IOException {
		URL url=new URL("https","www.baidu.com","/index.html");
		InputStream is=url.openStream();
//		Scanner input=new Scanner(is);
//		input.useDelimiter("/");
//		while(input.hasNext()){
//			System.out.println(input.next());
//		}
		int a=0;
		
		while((a=is.read())!=-1){
			System.out.print((char)a);
		}
	}
}
3.HTTP

超文本传输协议

URLConnection封装访问远程网络资源一般方法的类

通过它建立和远程服务的连接,检查远程资源的一些属性

常用方法

public int getContentLength() 取得内容的长度
public String getContentType() 取得内容的类型
public InputStream getInputStream() 取得连接的输入流

URLEncoder 类与 URLDecoder 类的常用方法:

public static Stringencode(String s,String enc)使用指定的编码机制将字符串转换为application/x-www-form-urlencoded格式

public static Stringdecode(String s,String enc)使 用 指 定 的 编 码 机 制 对application/x-www-form-urlencoded字符串解码

public class S3URLcoder {

	public static void main(String[] args) throws UnsupportedEncodingException {
		//按照特定字符编码编码
		String encode=URLEncoder.encode("黎冠猛", "GBK");
		System.out.println("GBK的编码为:"+encode);
		//按照特定字符编码解码
		String decode=URLDecoder.decode(encode, "GBK");
		System.out.println("GBK的解码为:"+decode);
	}
}
3.TCP

Java中使用套接字完成TCP程序的开发,使用此类可建立可靠的,双向的,持续的,点对点通信连接

Socket的程序开发中,服务器端使用serverSocket等待客户端的连接,客户端都是用Socket表示

1.ServerSocket

用在服务器端程序上的开发,用于接受客户端的请求

构造方法

public ServerSocket(int port) 构造创建 ServerSocket 实例,并指定监听端口

常用方法
public InetAddress getInetAddress() 返回服务器的 IP 地址

public Socket accept() 等待客户端连接,此方法连接之前一直阻塞public boolean isClosed() 返回 ServerSocket 的关闭状态
public void close() 关闭 ServerSocket

2.Socket

每一个Socket都表示一个客户端对象

构造方法

public Socket(String host,intport) 构造 Socket 对象,同时指定要连接服务器的主机名称及连接端口。

常用方法

public InputStream getInputStream() throws返回此套接字的输入流
public OutputStream getOutputStream() 返回此套接字的输出流

InetAddress getInetAddress() 得到Socket的InetAddress对象

int getLocalPort() 得到连接端口

boolean getKeepAlive() 判断是否和服务端保持连接

public boolean isClosed() 判断此套接字是否被关闭

public void close() 关闭此 Socket

服务端每次运行都要使用accept()方法等待客户端连接,此方法执行之后服务器将进入阻塞状态,直到客户端连接之后程序才可向下继续执行,此方法的返回值类型是Socket,

public class S4ServerSocket {
	public static void main(String[] args) throws IOException {
		Scanner input =new Scanner(System.in);
		ServerSocket sServer=new ServerSocket(3453);
		System.out.println("请输入发布的内容:");
		String str=input.nextLine();
		System.out.println("服务器等待客户端的连接");
		Socket sClient=sServer.accept();
		OutputStream os=sClient.getOutputStream();
		Writer w=new  OutputStreamWriter(os);
		w.write(str);
		
		w.close();
		os.close();
		sClient.close();
		sServer.close();
	}
}
public class S5Socket {
	public static void main(String[] args) throws UnknownHostException, IOException {
		Socket s=new Socket("localhost",3453);
		InputStream is=s.getInputStream();
		Reader r=new InputStreamReader(is);
		Scanner input=new Scanner(r);
		input.useDelimiter("/");
		while(input.hasNext()){
			System.out.println("客户端从服务器接收的内容:"+input.next());
		}
		r.close();
		is.close();
		s.close();	
	}
}
请输入发布的内容:
2345678
服务器等待客户端的连接

客户端从服务器接收的内容:2345678

客户端连接上服务器后会马上关闭,只能和一个客户端连接

3.使用多线程实现

ServerSocketThread

public class S6ServerSocketThread implements Runnable{
	public  static Socket client;
	
	public S6ServerSocketThread(Socket clinet) {
		this.client=clinet;
	}
	public void run() {
		try {
			OutputStream os=client.getOutputStream();
			InputStream is=client.getInputStream();

			Reader r=new InputStreamReader(is);
			PrintStream out=new PrintStream(os);
		
			BufferedReader br=new BufferedReader(r);
			boolean flag=true;
			while(flag){
				String s=br.readLine();
				System.out.println("读取到的信息:"+s);
				if(s==null) flag=false;
				else{
					if("bye".equals(s)){System.out.println("bye");	flag=false;}
					else {System.out.println("非bye");	out.println("回复信息ok:"+s);}
				}
				client.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	public static void main(String[] args) throws IOException {

		ServerSocket server=new ServerSocket(1234);
		boolean f=true;
		while(f){
			System.out.println("服务器正在运行,等待客户端的连接");
			client=server.accept();
			System.out.println("客户端已经连接");
			System.out.println("client:"+client);
			S6ServerSocketThread sst=new S6ServerSocketThread(client);
			Thread t=new Thread(sst);
			t.start();
		}
		server.close();

	}

	

}

SocketThread1

public class S7SocketThread1 {

	public static void main(String[] args) throws UnknownHostException, IOException {
		Scanner input =new Scanner(System.in);
		Socket client=new Socket("localhost",1234);

		InputStream is=client.getInputStream();
		OutputStream os=client.getOutputStream();
		
		Reader r=new InputStreamReader(is);
		BufferedReader br=new BufferedReader(r);//接收键盘数据
		PrintStream out=new PrintStream(os);//发送数据
		boolean f=true;
		while(f){
			System.out.println("输入信息:");
			String str=input.nextLine();
			out.println(str);//向服务器发送数据
			System.out.println("str:"+str);
			if("bye".equals(str)) {f=false;
									System.out.println("bye");}
			else {
				System.out.println("非bye");
				String echo=br.readLine();
				System.out.println(echo);
				
			}
		}
		br.close();
		client.close();

	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值