TCP服务端
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = inputStream.read(bytes);
String data = new String(bytes, 0, len);
System.out.println("收到数据:" + data);
socket.close();
serverSocket.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
TCP客户端
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 8888);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("哈哈,我来了".getBytes());
socket.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}