1.Java Socket(套接字)编程提供了在不同计算设备之间共享数据的功能。
- IP地址:IP地址是分配给网络节点(例如192.168.0.1)的唯一编号。它由0到255之间的八位字节组成。
- 协议:TCP、FTP、
- 端口号:端口号用于唯一标识不同的应用程序。它充当应用程序之间的通信端点。
- MAC地址:MAC(介质访问控制)地址是NIC(网络接口控制器)的唯一标识符。一个网络节点可以有多个NIC,但是每个都有唯一的MAC地址。
- 面向连接和无连接协议:在面向连接的协议中,确认是由接收方发送的。因此,它是可靠的但很慢。面向连接协议的一种实现是TCP协议。在无连接协议中,接收方不会发送确认。因此它不可靠,但速度很快。无连接协议的一种实现是UDP协议。
- Socket:Socket(套接字)是双向通信之间的端点。
Socket编程中的客户端必须知道两个信息:
- 服务短的IP地址
- 服务端端口号
要完成Socket编程,我们需要使用两个类:Socket和ServerSocket。
Socket类:用于通信客户端和服务器。通过此类,我们可以读写消息。
ServerSocket类:在服务器端使用。ServerSocket类的accept() 方法将阻止控制台,直到客户端连接为止。客户端成功连接后,它将在服务器端返回Socket的实例。
/**
* Java Socket编程(服务端)
*/
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}
/**
* Java Socket编程(客户端)
*/
import java.net.*;
import java.io.*;
public class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}
}
java.net.URL类提供了许多方法。URL类的重要方法如下:
方法 | 描述 |
public String getProtocol() | 返回URL的协议。 |
public String getHost() | 返回URL的主机名。 |
public String getPort() | 返回URL的端口号。 |
public String getFile() | 返回URL的文件名。 |
public String getAuthority() | 返回URL的权限。 |
public String toString() | 返回URL的字符串表示形式。 |
public String getQuery() | 返回URL的查询字符串。 |
public String getDefaultPort() | 返回URL的默认端口。 |
public URLConnection openConnection() | 返回URLConnection的实例,即与此URL关联的实例。 |
public boolean equals(Object obj) | 将URL与给定的对象进行比较。 |
public Object getContent() | 返回URL的内容。 |
public String getRef() | 返回URL的锚点或引用。 |
public URI toURI() | 返回URL的URI。 |
Java URLConnection类提供了许多方法,我们可以使用getInputStream() 方法显示网页的所有数据。getInputStream() 方法返回流中可以读取和显示的指定URL的所有数据。
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java URLConnection的例子
*/
import java.io.*;
import java.net.*;
public class Demo {
public static void main(String[] args){
try{
URL url=new URL("http://www.yiidian.com/java");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){
System.out.println(e);
}
}
}