热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

JavaSE网络编程TCP协议单线程聊天室

学习时间2021-04-07学习内容注意:本文在同一台机器上演示测试类1:importjava.io.IOException;importj

学习时间

2021-04-07


学习内容

注意:本文在同一台机器上演示

测试类1:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;public class Test1 {public static void main(String[] args) throws IOException {TCPClient();}public static void TCPClient() throws IOException {Socket socket = new Socket("192.168.1.xxx", 2222);//创建套接字并绑定端口OutputStream outputStream = socket.getOutputStream();//获取输出流Scanner scanner = new Scanner(System.in);System.out.println("请输入要发送的内容:");String s = scanner.nextLine();//要输入的内容outputStream.write(s.getBytes());//写入数据socket.close();//释放资源TCPServerClient();}public static void TCPServerClient() throws IOException {ServerSocket serverSocket = new ServerSocket(3333);//创建服务器端的Socket,并暴露端口号Socket accept = serverSocket.accept();//侦听连接InputStream inputStream = accept.getInputStream();//获取输入流byte[] bytes = new byte[1024];int read = inputStream.read(bytes);String s = new String(bytes, 0, read);//解析连接String ip = accept.getInetAddress().getHostAddress();System.out.println(ip + "发来信息:" + s);serverSocket.close();//释放资源TCPClient();}
}

测试类2:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;public class Test2 {public static void main(String[] args) throws IOException {TCPServerClient();}public static void TCPClient() throws IOException {Socket socket = new Socket("192.168.1.xxx", 3333);//创建套接字并绑定端口OutputStream outputStream = socket.getOutputStream();//获取输出流Scanner scanner = new Scanner(System.in);System.out.println("请输入要发送的内容:");String s = scanner.nextLine();//要输入的内容outputStream.write(s.getBytes());//写入数据socket.close();//释放资源TCPServerClient();}public static void TCPServerClient() throws IOException {ServerSocket serverSocket = new ServerSocket(2222);//创建服务器端的Socket,并暴露端口号Socket accept = serverSocket.accept();//侦听连接InputStream inputStream = accept.getInputStream();//获取输入流byte[] bytes = new byte[1024];int read = inputStream.read(bytes);String s = new String(bytes, 0, read);//解析连接String ip = accept.getInetAddress().getHostAddress();System.out.println(ip + "发来信息:" + s);serverSocket.close();//释放资源TCPClient();}
}

声明:


关于转载:

允许非商业用途转载,注明出处和链接即可。


推荐阅读
author-avatar
李程VS_328_302
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有