Socket通信要素
IP 地址:InetAddress
唯一的标识 Internet 上的计算机(通信实体)
本地回环地址(hostAddress):127.0.0.1 主机名(hostName):域名:localhost
端口(port)号标识正在计算机上运行的进程(程序)
不同的进程有不同的端口号
ip+port=socket
网络通信协议:
TCP协议:
使用TCP协议前,须先建立TCP连接,形成传输数据通道
传输前,采用“三次握手”方式,点对点通信,是可靠的
TCP协议进行通信的两个应用进程:客户端、服务端。
在连接中可进行大数据量的传输
传输完毕,需释放已建立的连接四次握手,效率低
UDP协议:
将数据、源、目的封装成数据包,不需要建立连接
每个数据报的大小限制在64K内 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的
可以广播发
送发送数据结束时无需释放资源,开销小,速度快
TCP协议:
public class test {
@Test
public void cclient() throws IOException {
InetAddress localhost = InetAddress.getByName("localhost");
Socket socket = new Socket(localhost, 8081);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("你好啊".getBytes());
socket.close();
}
@Test
public void server() throws IOException {
ServerSocket serverSocket = null;
InputStream inputStream = null;
serverSocket = new ServerSocket(8081);
Socket accept = serverSocket.accept();
inputStream = accept.getInputStream();
byte[] arr = new byte[1024];
int len;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
while ((len = inputStream.read(arr)) != -1) {
stream.write(arr, 0, len);
}
System.out.println(stream.toString());
serverSocket.close();
inputStream.close();
}
}
Url类
类 URL 和 URLConnection 提供了最高级网络应用。URL 的网络资源的位置来同一表示Internet 上各种网络资源
public void UrlTest() throws IOException {
URL url = new URL("http://localhost:8080/kk.jpg");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream();
byte arr [] = new byte[1024];
int len;
while ((len=inputStream.read(arr))!=-1){
fileOutputStream.write(arr,0,len);
}
urlConnection.disconnect();
inputStream.close();
fileOutputStream.close();
}
Httpclients 获取第三方Api内容
public List<User> getProactive(String pn,String sn,String date){
//请求体:json对象
JSONObject parametes = new JSONObject();
parametes.put("product_num",pn);
parametes.put("serial_num",sn);
parametes.put("date",date);
HttpPost post = new HttpPost("第三方API-url");
post.setHeader("Content-Type","application/json");
//动态token的话需要先获取,静态直接用即可;
post.setHeader("token标签","token内容");
String result;
List<User> userLiist=null;
try (CloseableHttpClient httpClient = HttpClients.createDefault()){
StringEntity stringEntity = new StringEntity(parametes.toString(), "utf-8");
post.setEntity(stringEntity);
CloseableHttpResponse response = httpClient.execute(post);
String status = response.getStatusLine().toString();//请求返回值,200/404
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
StringBuilder stringBuilder = new StringBuilder();
String line;
while((line=reader.readLine())!=null){
stringBuilder.append(line+"\n");
}
inputStream.close();
result=stringBuilder.toString();
userLiist= JSONArray.parseArray(result,User.class);
} catch (IOException e){
e.printStackTrace();
}
return userLiist;
}