Java基于socket实现的客户端和服务端通信功能完整实例
作者:爱代码也爱生活 发布时间:2023-11-22 12:12:13
标签:Java,socket,通信
本文实例讲述了Java基于socket实现的客户端和服务端通信功能。分享给大家供大家参考,具体如下:
以下代码参考马士兵的聊天项目,先运行ChatServer.java实现端口监听,然后再运行ChatClient.java
客户端实例
ChatClient.java
package socketDemo;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("localhost", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
/*
* try { bConnected = false; tRecv.join(); } catch(InterruptedException
* e) { e.printStackTrace(); } finally { try { dos.close(); dis.close();
* s.close(); } catch (IOException e) { e.printStackTrace(); } }
*/
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
// taContent.setText(str);
tfTxt.setText("");
try {
// System.out.println(s);
dos.writeUTF(str);
dos.flush();
// dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while (bConnected) {
String str = dis.readUTF();
// System.out.println(str);
taContent.setText(taContent.getText() + str + '\n');
}
} catch (SocketException e) {
System.out.println("退出了,bye!");
} catch (EOFException e) {
System.out.println("推出了,bye - bye!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
socket服务端代码
ChatServer.java
package socketDemo;
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.out.println("端口使用中....");
System.out.println("请关掉相关程序并重新运行服务器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
try {
while (started) {
Socket s = ss.accept();
Client c = new Client(s);
System.out.println("a client connected!");
new Thread(c).start();
clients.add(c);
// dis.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("对方退出了!我从List里面去掉了!");
// e.printStackTrace();
}
}
public void run() {
try {
while (bConnected) {
String str = dis.readUTF();
System.out.println(str);
for (int i = 0; i < clients.size(); i++) {
Client c = clients.get(i);
c.send(str);
// System.out.println(" a string send !");
}
/*
* for(Iterator<Client> it = clients.iterator();
* it.hasNext(); ) { Client c = it.next(); c.send(str); }
*/
/*
* Iterator<Client> it = clients.iterator();
* while(it.hasNext()) { Client c = it.next(); c.send(str);
* }
*/
}
} catch (EOFException e) {
System.out.println("Client closed!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null)
dis.close();
if (dos != null)
dos.close();
if (s != null) {
s.close();
// s = null;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
本机测试运行结果:
关闭客户端窗口后,提示信息如下:
希望本文所述对大家java程序设计有所帮助。
来源:https://blog.csdn.net/nuli888/article/details/51884931
0
投稿
猜你喜欢
- 一、二进制读写类:1、BinaryReader/BinaryWriter:二进制读写BinaryReader:用特定的编码将基元数据类型读作
- 今天看了一下数据结构,一个练习就是构建哈夫曼树,就顺手用C#写了一个。static void Main(string[] args){ &n
- 对称加密算法是应用较早的加密算法,技术成熟。在对称加密算法中,数据发信方将明文(原始数据)和加密密钥(mi yue)一起经过特殊加密算法处理
- 通过 SpringBoot 实现了表单下的文件上传,前后端分离情况下的文件上传。本案例不连接数据库,只做基本的文件上传操作。在 Spring
- 以最终客户的角度来看,JAR文件就是一种封装,他们不需要知道jar文件中有多少个.class文件,每个文件中的功能与作用,同样可以得到他们希
- 改进思考正常实现流程应该为继承ClassLoader虚拟类,并重写其loadClass方法和findClass方法,并在loadClass方
- 1、来源random.nextInt() 为 java.util.Random类中的方法; Math.random() 为 java.lan
- 本文实例讲述了C#把数组中的某个元素取出来放到第一个位置的实现方法。分享给大家供大家参考。具体分析如下:如何取出数组中符合某种条件的元素,然
- 一、判断字母string str = Console.ReadLine();if (char.isLetter(str)){}else if
- 本文介绍了spring整合JMS实现同步收发消息(基于ActiveMQ的实现),分享给大家,具体如下:1. 安装ActiveMQ注意:JDK
- 背景Arthas是阿里巴巴开源的应用诊断利器,提供了profiler命令,可以生成热点火焰图。通过采样录制调用链路来做性能分析,极大提升了线
- 先来说一说我们为什么要用这个东西啊!比如,我们现在有这样了个问题要解决:这样,我们就要用到中间消息间了然后我们就说一下什么是中间消息间吧。采
- 1 @SpringBootApplication自动配置原理@SpringBootApplication是一个组合注解,主要由@Compon
- 一、前期准备我们要在IDEA上创建一个新的项目,创建好一个项目后,我们需要创建4个包,分别是英雄包,装备包,铭文包,野怪包,皮肤包然后我们就
- 导读 Spring Boot方式的项目开发已经逐步成为Java应用开发领域的主流框架,它不仅可以方便地创建生产级的Spring应用
- Java面向对象之猜拳游戏,供大家参考,具体内容如下1 要求与电脑进行猜拳并记录分数。2 Computer.java 源代码(电脑自动随机出
- 前言需求是上传Excel文件并读取Excel文件中的内容,根据获取的数据执行完某些业务操作后再将一些数据写回到excel中。前台使用Form
- 一、概要1.Java虚拟机(Jvm)是什么?2.Java虚拟机是用来干什么的?3.Java虚拟机它的体系结构是什么样子的?4.Java虚拟机
- 1.问题描述在我引入SpringCloud-gateway,运行时报错如下:org.springframework.beans.factor
- 1:首先我们看一下数据库的表:这里的pid就是代表他的父节点id,如果没有父节点,那么pid就是0,上面的表就可以看作是一个tree结构,那