socket通信入门-TCP

最近需要做一个微信小程序,有发卷和收卷的功能。要实现一个聊天室,将所有的小程序链接起来,做到统一收发试卷,所以研究了一下socket。

1.tcp版

代码

public class Server {

public static void main(String[] args) throws IOException {
	//1.创建ServerSocket 并制定监听端口
	int port = 8888;
	ServerSocket serverSocket = new ServerSocket(port);
	//2.创建Socket,存储监听到的链接
	Socket socket = new Socket();
	System.out.println("*******服务器已经启动了,开始监听8888端口********");

	int count = 0;
	while(true){
		socket = serverSocket.accept(); //程序会进入到阻塞状态,直到接收到客户端发送的socket
		count ++;
		System.out.println("服务端:监听到第"+count+"个socket");
		//将接受到的socket扔到另一个线程里去处理,然后继续监听
		ServerThread thread = new ServerThread(socket);
		thread.start();
	}
}

}

public class ServerThread extends Thread {
private Socket socket = null;

public ServerThread(Socket socket){
	this.socket = socket;
}

@Override
public void run() {
	try {
		//获取客户算发送的字节流数据
		InputStream is = socket.getInputStream();
		//获取字符流数据
		InputStreamReader isr = new InputStreamReader(is);
		//创建缓存
		BufferedReader br = new BufferedReader(isr);
		//打印客户端发送的数据
		String info = null;
		while((info = br.readLine())!=null){
			System.out.println(info);
		}

		socket.shutdownInput();
		br.close();
		isr.close();
		is.close();
		socket.close();
		
	} catch (IOException e) {
		e.printStackTrace();
	}
}

}

public class Client {
public static void main(String[] args) throws IOException {
//指定访问的主机
InetAddress address = InetAddress.getByName(“localhost”);
int port = 8888;
Socket socket = new Socket(address, port);
OutputStream os = socket.getOutputStream();

	PrintWriter pw = new PrintWriter(os);
	pw.write("我是客户端:用户名:123,密码:123");
	pw.flush();
	pw.close();
	os.close();
	socket.close();
}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值