Nested words: Socket: provides an interface for the program to connect to the outside world
Server socket: ServerSocket
client socket: Socket
here to open two eclipse or other start the server first, and then start the client
package dao;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Clict {
public static void main(String[] args) {
try {
Socket clict=new Socket("127.0.0.1",1100);//1100是端口号
System.out.println("服务器连接成功");
OutputStream out=clict.getOutputStream();
String message="服务器你好,我是客户端";
//写
out.write(message.getBytes());//把信息写进去
//读
InputStream inputStream=clict.getInputStream();
byte[] bt=new byte[1024];
int len =inputStream.read(bt);
System.out.println("服务器发来消息:"+new String(bt,0,len));
clict.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(1100);
System.out.println("服务器启动成功,等待用户接入!");
Socket clict=server.accept();//等待用户端接入
System.out.println("有客户端接入,客户端的ip:"+clict.getInetAddress());//获取客户端的地址
InputStream inputStream=clict.getInputStream();
byte[] bt=new byte[1024];
int len =inputStream.read(bt);
System.out.println("客户端发来消息:"+new String(bt,0,len));
OutputStream out=clict.getOutputStream();
String message="客户端你好,我是服务器";
out.write(message.getBytes());
clict.close();
server.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201012210200921.png#pic_center)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201012210213508.png#pic_center)