网络Socket

网络:
网络得三要素   
    1.ip地址
    2.端口号
    3.通信协议 udp tcp
iP地址对应得对象inetAddress
 
InetAddress.getLocalHost()     
    得到本机电脑得 电脑名/ip地址
 
传输协议
UDP:像发短信,有字数限制
    数据大小限制在64k内
    效率较高,不安全,容易丢包
TCP
    像打电话,需要接通
    效率较低,数据传输安全
    需要三次握手
 
三次握手:
  发送  第一次:建立连接 发送链接请求
  返回:第二次:确认链接,答应链接
发送,确认建立链接
四次分手:
两端都需要断开链接
各分别发送断开链接请求,都回复好的 断开链接 两端各两次就是4次
 
Socket的双端通信
客户端:Socket
服务端:ServerSocket
从里面获取输入/输出流之后 读取数据作出相应的调整
 
客户端:
public class SocketDemo01 {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1",10086);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("天天都需要你爱".getBytes());
 
 
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int read =0;
while ((read=inputStream.read(bytes))!=-1){
System.out.println(new String(bytes,0,read));
}
 
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
 
}
}
}
 
服务端:
public class SocketInput {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(10086);
Socket accept = serverSocket.accept();
InputStream inputStream = accept.getInputStream();
byte[] bytes = new byte[1024];
int read =inputStream.read(bytes);
System.out.println(new String(bytes,0,read));
 
OutputStream outputStream = accept.getOutputStream();
outputStream.write("收到了数据".getBytes());
 
outputStream.close();
inputStream.close();
accept.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
posted @ 2021-03-30 16:52  七七负柒柒  阅读(67)  评论(0)    收藏  举报