客户端
package com.woniuxy.tcpip;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class ClientDemo {
public static void main(String[] args) {
// 目标主机 ip
String aimIP = "localhost";
// 目标主机的端口
int aimPort = 554;
// 定义需要发送的内容
String content = "你好呀!";
// 套接字
Socket socket = null;
// 输出流
OutputStream os = null;
try {
/*
* 关键三步
*/
// 创建 Socket 对象
socket = new Socket(aimIP, aimPort);
// 获取 Socket 输出流
os = socket.getOutputStream();
// 将数据填入 Socket 对象的输出流中就可以了
os.write(content.getBytes());
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// 释放支援,总是执行
try {
// 先释放 Socket对象的输出流,再释放 Socket对象
os.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务器
package com.woniuxy.tcpip;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String[] args) {
// 监听端口
int listenPort = 554;
// 创建服务器套接字
ServerSocket serverSocket = null;
// 接收客服端套接字
Socket clienSocket = null;
// 接收客服端输入流
InputStream inputStream = null;
try {
serverSocket = new ServerSocket(listenPort);
// 调用阻塞方法 ,获取客服端传入的套接字
clienSocket = serverSocket.accept();
// 获取客服端 ip
System.out.println(clienSocket.getInetAddress());
// 获取输入流
inputStream = clienSocket.getInputStream();
byte[] con = new byte[1024];
int len = -1;
while ((len = inputStream.read(con)) != -1) {
System.out.println(new String(con, 0, len));
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
inputStream.close();
clienSocket.close();
serverSocket.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}