Java网络编程
TCP特点:
- 通讯之前要先建立连接
- 是可靠的协议,效率慢
- 有序性
UDP特点:
- 只管发送,不考虑对方是否接收的到
- 不可靠协议,效率高(QQ消息,语音,视频,网络游戏传输)
网络编程(socket编程)
java.net
- ServerSocket和Client是实现TCP连接的
- 端口号:Port number,65536个端口号 用来区分同一台电脑上的不同应用程序,系统一般使用1024以下的端口。
- tcp端口有65536,udp端口也有65536个。
各种API:
-
InetAddress
- InetAddress.getByName("www.qq.com");
- InetAddress.getByName("127.0.0.1");
- InetAddress.getLocalHost();
- InetAddress.getLocalHost().getHostName();
- InetAddress.getLocalHost().getHostAddress();
-
Socket:代表网络连接
-
客户端:Socket s = new Socket(“127.0.0.1”,8000);
/**简单的Socket客户端 功能为:发送字符串“Hello”到服务器端,并打印出服务器端的反馈*/
public class SimpleSocketClient {
public static void main(String[] args) {
Socket socket = null;
InputStream is = null;
OutputStream os = null;
// 服务器端IP地址
String serverIP = "127.0.0.1";
// 服务器端端口号
int port = 10000;
// 发送内容
String data = "Hello";
try {
// 建立连接
socket = new Socket(serverIP, port);
// 发送数据
os = socket.getOutputStream();
os.write(data.getBytes());
// 接收数据
is = socket.getInputStream();
byte[] b = new byte[1024];
int n = is.read(b);
// 输出反馈数据
System.out.println("服务器反馈:" + new String(b, 0, n));
} catch (Exception e) {
e.printStackTrace(); // 打印异常信息
} finally {
try {
// 关闭流和连接
is.close();
os.close();
socket.close();
} catch (Exception e2) {
}
}
}
} -
服务器:ServerSocket ss = new ServerSocket(port);
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/** 服务器 功能:将客户端发送的内容反馈给客户端*/
public class SimpleSocketServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
OutputStream os = null;
InputStream is = null;
// 监听端口号
int port = 10000;
try {
// 建立连接
serverSocket = new ServerSocket(port);
// 获得连接
socket = serverSocket.accept();
// 接收客户端发送内容
is = socket.getInputStream();
byte[] b = new byte[1024];
int n = is.read(b);
// 输出
System.out.println("客户端发送内容为:" + new String(b, 0, n));
// 向客户端发送反馈内容
os = socket.getOutputStream();
os.write(b, 0, n);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭流和连接
os.close();
is.close();
socket.close();
serverSocket.close();
} catch (Exception e) {
}
}
}
}
-
-
UDP数据连接
-
DatagramSocket. 实现“网络连接”,包括客户端网络连接和服务器端网络连接。
-
DatagramPacket. 类实现对于网络中传输的数据封装,也就是说,该类的对象代表网络中交换的数据。
-
UDPServer:
public class UDPServer {
public static void main(String[] args) throws Exception {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
DatagramSocket ds = new DatagramSocket(7899);
while (true) {
ds.receive(dp);
System.out.println(new String(buf, dp.getLength()));
}}
}
-
UDPClient:
public class UDPClient {
public static void main(String[] args) throws Exception {
String s = "123";
byte[] buf = s.getBytes();DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("192.168.20.249", 7899));
DatagramSocket ds = new DatagramSocket(9999);
ds.send(dp);
ds.close();}
}
-

浙公网安备 33010602011771号