package com.wet.TCP;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*服务器端
*/
public class TCPServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8080); // 创建绑定到特定端口的服务器套接字
Socket s = ss.accept(); // 侦听并接受到此套接字的连接
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
in.read(buf);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("来自客户端的信息:" + new String(buf).trim() + " 时间:"
+ sdf.format(new Date()));
OutputStream out = s.getOutputStream();
out.write("你好客户端".getBytes());
in.close();
out.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.wet.TCP;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*客户端
*/
public class TCPClient {
public static void main(String[] args) {
try {
// 创建一个流套接字并将其连接到指定 IP 地址的指定端口号
Socket s = new Socket("127.0.0.1", 8080);
OutputStream out = s.getOutputStream();
out.write("你好服务器".getBytes());
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
in.read(buf);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("来自服务器的信息:" + new String(buf).trim() + " 时间:"
+ sdf.format(new Date()));
in.close();
out.close();
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
958

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



