通过JAVA实现TCP简单对话
服务器端实现步骤:
建立服务的端口 ServerSocket
等待用户连接 Socket
接收用户消息 InputSteam
使用管道流转换数据 ByteArrayOutputStream
package ip.socket;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
// 服务器
public class server {
public static void main(String[] args) {
ByteArrayOutputStream baos = null;
InputStream is = null;
Socket socket = null;
ServerSocket serverSocket = null;
try {
//1.服务器的地址
serverSocket = new ServerSocket(9999);
while(true){
// 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());
}
} 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();
}
}
}
}
}
客户端的实现步骤:
连接服务器 Socket
发送消息 OutputStream
package ip.socket;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
// 客户端
public class customer {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
// 1.连接服务器的地址
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
// 2.创建一个socket连接
socket = new Socket(serverIP,port);
// 3.使用 I/O流 发送消息
os = socket.getOutputStream();
os.write("你好,世界!".getBytes());
} 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();
}
}
}
}
}
先运行服务器端代码,再运行客户端代码,运行结果如下:
你好,世界!