以下代码实现了客户端发送消息到服务器,服务器接收到消息并读取输出,然后写出到客户端客户端接收到输出。
服务端代码示例
- 服务器建立通信ServerSocket
- 服务器建立Socket接收客户端连接
- 建立IO输入流读取客户端发送的数据
- 建立IO输出流向客户端发送数据消息
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
//服务端
public class TcpServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
OutputStream os = null;
try {
//1、创建server服务,监听9999端口
serverSocket = new ServerSocket(9999);
//2、等待客户端连接(侦听要连接到此套接字并接受它)
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("utf-8") + "(接收时间:" + System.currentTimeMillis() / 1000 + ")");
//4、通知客户端,接收完毕
socket.shutdownInput();
//5、休眠3秒后回复消息到客户端
TimeUnit.SECONDS.sleep(3);
os = socket.getOutputStream();
String message = "在的,有啥事(回复时间:" + (System.currentTimeMillis() / 1000 + ")");
os.write(message.getBytes("utf-8"));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (baos != null) {
baos.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端代码示例
- 创建Socket通信,设置通信服务器的IP和Port
- 建立IO输出流向服务器发送数据消息
- 建立IO输入流读取服务器发送来的数据消息
//客户端
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1、创建一个socket连接
socket = new Socket("127.0.0.1", 9999);
//2、 发送消息
os = socket.getOutputStream();
os.write("你好,在吗?".getBytes("utf-8"));
//3、通知服务器,发送完毕
System.out.println("发送时间:" + System.currentTimeMillis() / 1000);
socket.shutdownOutput();
//4、等待服务器返回消息
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 (Exception e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}