Java基于socket实现的客户端和服务端通信功能完整实例
作者:爱代码也爱生活 时间:2023-11-22 12:12:13
本文实例讲述了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
标签:Java,socket,通信
0
投稿
猜你喜欢
详解Android studio中正确引入so文件的方法
2022-06-17 23:21:32
解析:android 如何从JPEG生成BufferedImage
2022-06-03 20:11:50
java设置session过期时间的实现方法
2022-02-18 20:25:29
springMVC+velocity实现仿Datatables局部刷新分页方法
2022-06-20 01:05:22
java中LinkedList使用迭代器优化移除批量元素原理
2021-12-05 11:26:07
解决springboot遇到autowire注入为null的问题
2022-04-15 02:37:59
使用HTTPclient保持长连接
2023-10-17 12:29:34
RxJava中多种场景的实现总结
2023-01-09 05:39:02
Java @Deprecated注解的作用及传递性
2023-08-11 12:55:05
Java基于Tcp协议的socket编程实例
2022-03-08 00:04:13
C#使用集合实现二叉查找树
2023-06-01 06:17:21
Android列表组件ListView使用详解之动态加载或修改列表数据
2023-10-01 16:14:38
c# 编写的简单飞行棋游戏
2022-12-05 05:10:59
thymeleaf实现前后端数据交换的示例详解
2023-04-18 12:02:54
Java SSH 秘钥连接mysql数据库的方法
2022-07-11 21:23:18
springboot如何实现自动装配源码解读
2023-11-10 15:44:20
Android 使用viewpager实现无限循环(定时+手动)
2023-12-09 07:43:56
Android实现圆形渐变加载进度条
2021-07-17 18:38:06
关于Spring中的三级缓存解析
2022-08-20 15:31:06
SpringBoot分页查询功能的实现方法
2023-07-14 02:22:21