socket原理
一、tcp传输协议
1.tcp:Transmission Control Protocol(传输控制协议)
2.面向连接的能够提供可靠的流式数据传输的协议。类似于打电话的过程。
3.URL URLConnection,Socket,ServerSocket等类都使用tcp协议进行网络通信
二、socket通讯
1.网络上两个程序通过一个双向的通讯连接实现数据的交换,这个双向链路的一端成为socket。
2.socket 通常用来实现客户方和服务方的链接。
image.png
image.png
通讯实现
一、创建socket
1.Socket()
2.Socket(IntAddress address,int port)
3.Socket (String host,int port)
4.Socket (IntAddress host, int port, IntAddress localAddr,int localPort)
5.Socket (String host, int port, InetAddress loocalAddr,int localPort)
客户端socket的建立
import java.io.IOException;
import java.net.Socket;
public class socket {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 2000);
}catch (IOException e){
System.out.println("Error:"+e);
}
}
}
服务端socket的建立
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class socketserver {
public static void main(String[] args) {
ServerSocket server = null;
try {
server = new ServerSocket(2000);
}catch (IOException e){
System.out.println("can not listen to :"+e);
}
Socket socket = null;
try {
socket = server.accept();
}catch (IOException e){
System.out.println("Error:"+e);
}
}
}
打开输入/输出流
PrintStream os = new
PrintStream(new BufferedOutputStream(socket.getOutputStream()));
DataInputStream is =new
DataInputStream(socket.getInputStream());
PrintWriter out = new
PrintWriter(socket.getOutputStream(),true);
BufferedReader in = new
BufferedReader(new InputStreamReader(socket.getInputStream()));