public static void main(String[] args) throws IOException {
// 创建客户端Socket对象
Socket socket = new Socket(InetAddress.getLocalHost(), 10010);
// 获取输出流对象
OutputStream out = socket.getOutputStream();
// 写出数据
out.write("tcp, im coming!".getBytes());
// 接收服务端返回的数据
InputStream in = socket.getInputStream();
// 一次读取一个字节数组
byte[] bys = new byte[1024];
int len;
len = in.read(bys);
// 转换为字符串
String s = new String(bys, 0, len);
System.out.println("客户端接收到服务端响应:"+s);
// 释放资源
socket.close();
}
}
public class TCPServer {
public static void main(String[] args) throws IOException {
// 创建服务端ServerSocket
ServerSocket serverSocket = new ServerSocket(10010);
// 监听连接
System.out.println("服务端启动...");
Socket socket = serverSocket.accept();
// 获取输入流对象
InputStream in = socket.getInputStream();
// 读取数据, 一次一个字节数组
byte[] bys = new byte[1024];
int len;
len = in.read(bys);
// 转为字符串
String s = new String(bys, 0, len);
System.out.println("服务端接收到数据:" + s);
// 将字符串转为大写
s = s.toUpperCase();
// 获取输出流, 写回客户端
OutputStream out = socket.getOutputStream();
out.write(s.getBytes());
// 释放资源
socket.close();
}
}
用户登录客户端
*/
public class LoginClient {
public static void main(String[] args) throws IOException {
// 创建客户端Socket
Socket socket = new Socket("lishaoqing", 8888);