1、TCP/UDP: TCP:安全的、效率较低的固定连接 UDP:不安全、高效在线影视/聊天室等
2、Socket套接字,用于实现建立计算机之间的TCP链接。
一、最简单的socket编程
package ServerAndClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(9527); //创建服务器套接字
System.out.println("服务器启动完毕");
Socket socket = server.accept();
System.out.println("创建客户链接");
InputStream input = socket.getInputStream(); //获取socket输入
InputStreamReader isReader = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isReader);
while (true) {
String str = reader.readLine();
if (str.equals("exit")) {
break;
System.out.println("接收内容" + str);
}
System.out.println("链接断开");
reader.close(); //按顺序关闭链接
isReader.close();
input.close();
socket.close();
server.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package ServerAndClient;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("loclhost", 9527); //创建连接服务器的socket
OutputStream out = socket.getOutputStream(); //获取socket输出
out.write("这是我第一次访问服务器".getBytes());
out.write("Hello\n".getBytes());
out.write("exit\n".getBytes()); //发送退出信息
} catch (UnknownHostException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
二、最简单的额UDP编程
package UDP;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class client_udp {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("127.0.1");
DatagramPacket socket = new DatagramPacket();
byte[] data = "hello, 这是我第一次访问服务器".getBytes();
DatagramPacket dp = new DatagramPacket(data, data.length, address, 9527);
socket.send(dp);
} catch (UnknownHostException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
package UDP;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Server_udp {
public static void main(String[] args) {
byte[] buff = new byte[1024];
DatagramPacket dp1 = new DatagramPacket(buf, buf.length);
try {
DatagramSocket socket = new DatagramSocket(9527);
socket.receive(dp1);
int length = dp1.getLength();
String message = new String(dp1.getData(), 0, length);
String ip = dp1.getAddress().getHostAddress();
System.out.println("从" + ip + "发来了消息" + message);
} catch (SocketException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}