软件编程
位置:首页>> 软件编程>> java编程>> java学习之利用TCP实现的简单聊天示例代码

java学习之利用TCP实现的简单聊天示例代码

作者:猿上生活  发布时间:2021-07-13 00:43:18 

标签:java,tcp,聊天

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();
 }
}
}
}

来源:http://www.cnblogs.com/xuzhaocai/archive/2017/12/24/8099681.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com