嵌套字:Socket:提供给程序可以对外进行连接的接口
服务器的套接字:ServerSocket
客户端的套接字:Socket
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)