Java网络编程
IP地址
- 本机localhost:127.0.0.1
- InetAddress
- 通过静态方法获取实例
Socket
- InetSocketAddress
简单TCP通信
Server:
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1.建立服务端口
serverSocket = new ServerSocket(9999);
while (true) {
//2.等待客户端连接,获取客户端socket
socket = serverSocket.accept();
//3.接收用户消息
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
System.out.println(baos.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(baos != null){
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(serverSocket != null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Client:
public static void main(String[] args) {
Socket socket = null;
OutputStream os= null;
try {
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
//1.连接服务器
socket = new Socket(serverIP, port);
//2.发送消息
os = socket.getOutputStream();
os.write("你好".getBytes(StandardCharsets.UTF_8));
socket.shutdownOutput();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
简单UDP通信
Server:
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket(9090);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);//阻塞接收
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0, packet.getLength()));
socket.close();
}
Client:
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket();
String msg = "你好";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
socket.send(packet);
}
URL
通过URL获取资源:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.getInputStream();
...
urlConnection.disconnect();