客户端发送内容到服务端,服务端将内容打印到控制台
package internet;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author 苗晓强
* @date 2023/8/6 15:07
*/
public class TCPTest {
@Test
public void client(){
Socket socket = null;
OutputStream outputStream = null;
try {
//服务端的IP地址
InetAddress inetAddress = InetAddress.getByName("192.168.126.1");
//服务端的端口号
int port = 8989;
socket = new Socket(inetAddress,port);
outputStream = socket.getOutputStream();
outputStream.write("你好,我是客户端".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void server(){
//服务端Socket类 ServerSocket
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
try {
int port = 8989;
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
inputStream = socket.getInputStream();
int len;
byte [] buffer = new byte[1024];
//避免出现中文乱码 使用 ByteArrayOutputStream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer,0,len);
}
System.out.println(socket.getInetAddress().getHostAddress());
System.out.println(byteArrayOutputStream.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
JavaTCP客户端与服务器通信示例
本文展示了如何在Java中实现TCP客户端向192.168.126.1的8989端口发送消息,并捕获服务器响应,包括客户端和服务端的Socket操作及异常处理。
702

被折叠的 条评论
为什么被折叠?



