TCP
TCP协议是面向连接、保证高可靠性(数据无丢失、数据无失序、数据无错误、数据无重复到达)传输层协议。
TCP通过三次握手建立连接,通讯完成时要拆除连接,由于TCP是面向连接的所以只能用于端到端的通讯。
本文主要介绍了java利用TCP实现简单聊天的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
示例代码
使用tcp协议实现的简单聊天功能(非常简单的)
思想:使用2个线程,一个线程是用来接收消息的,另一个线程是用来发消息的。
客户端Demo代码:
public class SendDemo { public static void main(String[] args) throws Exception{ Socket socket= new Socket(InetAddress.getLocalHost(),8888); SendImpl sendImpl= new SendImpl(socket); //发送的线程 new Thread(sendImpl).start(); //接收的线程 ReciveImpl reciveImpl=new ReciveImpl(socket); new Thread(reciveImpl).start(); } }
服务器端Demo代码:
public class ServerDemo { public static void main(String[] args) throws Exception { ServerSocket serverSocket =new ServerSocket(8888); Socket socket=serverSocket.accept(); SendImpl sendImpl= new SendImpl(socket); new Thread(sendImpl).start(); ReciveImpl reciveImpl=new ReciveImpl(socket); new Thread(reciveImpl).start(); } }
发送线程的Demo代码:
public class SendImpl implements Runnable{ private Socket socket; public SendImpl(Socket socket) { this.socket=socket; // TODO Auto-generated constructor stub } @Override public void run() { Scanner scanner=new Scanner(System.in); while(true){ try { OutputStream outputStream = socket.getOutputStream(); String string= scanner.nextLine(); outputStream.write(string.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
接收线程的Demo代码:
public class ReciveImpl implements Runnable { private Socket socket; public ReciveImpl(Socket socket) { this.socket=socket; // TODO Auto-generated constructor stub } @Override public void run() { while(true ){ try { InputStream inputStream = socket.getInputStream(); byte[] b=new byte[1024]; int len= inputStream.read(b); System.out.println("收到消息:"+new String(b,0,len)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载像素火影骨架佐助 (Perseverance Fire Shadow)手机版v1.16
下载要塞英雄 安卓版v33.20.0-39082670-Android
下载梦想城镇vivo最新版本 安卓版v12.0.1
梦想城镇vivo版是这款卡通风模拟经营类手游的渠道服版本,玩
怦然心动的瞬间 安卓版v1.0
怦然心动的瞬间是一款真人向的恋爱互动游戏,在游戏中玩家将扮演
曼尼汉堡店游戏 安卓版v1.0.3
曼尼汉堡店是一款非常好玩的精品恐怖类型冒险游戏,在这款游戏中
现代总统模拟器去广告版 安卓版v1.0.46
现代总统模拟器是一款休闲养成类游戏,可能对于不少的玩家来说都
现代总统模拟器付费完整版 安卓版v1.0.46
现代总统模拟器高级版在商店是需要付费的,相对于普通版本,高级