网络编程——TCP连接
TCP在双方传输数据前,发送方先请求建立连接,接收方同意建立连接后才能传输数据。(打电话:先拨号,等对方同意接听后,才能交流)。。。高可靠性
UDP不需要建立连接(发短信)。不可靠,可能出现数据丢失等,但效率高,实时性高。
————————————————————————————————————————————————————————————————————————————
服务器端:
import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class ServerSocketTest { public static void main(String[] args) throws IOException { // 新建一个服务器端的套接字 Server端监听10000端口 ServerSocket serverSocket = new ServerSocket(10000); // 建立连接,此时进入阻塞状态 Socket socket = serverSocket.accept(); System.out.println("Connected: " + socket.getRemoteSocketAddress()); // socket从客户端读取数据 InputStream inputStream = socket.getInputStream(); byte[] b = new byte[1024]; int length = inputStream.read(b); System.out.println(length + " Bytes Received"); } }
客户端代码:
import java.io.IOException; import java.io.OutputStream; import java.net.Socket; public class ClientSocketTest { public static void main(String[] args) throws IOException { //新建一个客户端的套接字
Socket socket = new Socket("127.0.0.1", 10000); // 用socket往服务器端发送数据
OutputStream outputStream = socket.getOutputStream(); byte[] b = new byte[2]; outputStream.write(b); } }
运行结果:
Connected: /127.0.0.1:60361 2 Bytes Received