聊天程序设计实验报告
更新时间:2023-06-10 12:05:01 阅读量: 实用文档 文档下载
JAVA语言,聊天室实验报告
XX
专业名称
实 验 室
实验课程
实验名称
姓 名 学 号 同组人员
实验日期 XXXX大学 软件工程 2号实验楼201室 JAVA高级程序设计 聊天程序设计(客户端、服务端) 无 2013年12月12日
JAVA语言,聊天室实验报告
一、实验目的
掌握基于TCP、UDP协议的聊天服务器端与客户端程序设计,掌握Socket, ServerSocket,
DatagramSocket, DatagramPacket类的使用。
二、实验原理
TCP和UDP协议的支持。ServerSocket和Socket的使用。
三、实验内容
实验截图
JAVA语言,聊天室实验报告
代码
import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import .ServerSocket;
import .Socket;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author
*/
public classextends javax.swing.JFrame {
private ServerSocket server;
private int = 0;
private char[] chatBuf = new char[2048];
private String chatIpAddress = "127.0.0.1";
private final int chatPort = 5200;
private HashMap<String, Vector<IMessage>> chatRecordsMap;
//private HashMap<String, Integer> chatRecordHMap;
public TalkHome() {
initComponents();
chatRecordsMap = new HashMap<String, Vector<IMessage>>();
//chatRecordHMap = new HashMap<String, Integer>();
try {
server = new ServerSocket(Integer.valueOf(chatPort));
} catch (IOException ex) {
Logger.getLogger(TalkHome.class.getName()).log(Level.SEVERE,
null, ex);
}
new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Socket socket = server.accept();
JAVA语言,聊天室实验报告
BufferedReader sin = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
int tmp_len = -1;
StringBuilder chatStrBuilder = new StringBuilder();
while((tmp_len = sin.read(chatBuf)) != -1) {
chatStrBuilder.append(chatBuf, 0, tmp_len);
}
addMessage(socket.getInetAddress().getHostAddress(),
chatStrBuilder.toString(), false);
sin.close();
socket.close();
} catch (IOException ex) {
Logger.getLogger(TalkHome.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}).start();
}
private void reChatWindow(String ipAddress) {
System.out.println(ipAddress);
Vector<IMessage> chatRecords = chatRecordsMap.get(ipAddress);
jTextArea1.setText("");
if(chatRecords == null) {
chatRecords = new Vector<IMessage>();
chatRecordsMap.put(ipAddress, chatRecords);
}
else {
for(IMessage iMess : chatRecords) {
if(iMess.ismyself) {
jTextArea1.append("我 "+iMess.dateString+"
"+iMess.timeString+"\n"+iMess.messString+"\n\n");
}
else {
jTextArea1.append("TA " +iMess.dateString+"
"+iMess.timeString+"\n"+iMess.messString+"\n\n");
}
}
}
}
private void addMessage(final String ipAddress, String messString, boolean
ismyself) {
Vector<IMessage> chatRecords = chatRecordsMap.get(ipAddress);
if(chatRecords == null) {
JAVA语言,聊天室实验报告
chatRecords = new Vector<IMessage>();
chatRecordsMap.put(ipAddress, chatRecords);
}
final IMessage iMessage = new IMessage(messString, ismyself);
chatRecords.add(iMessage);
if(ismyself) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Socket sendMessage = new Socket(ipAddress, chatPort);
PrintWriter sendWindow = new
PrintWriter(sendMessage.getOutputStream());
sendWindow.print(iMessage.messString);
sendWindow.flush();
sendWindow.close();
sendMessage.close();
jTextArea1.append("我 " +iMessage.dateString+"
"+iMessage.timeString+"\n"+iMessage.messString+"\n\n");
} catch (IOException ex) {
Logger.getLogger(TalkHome.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
}
else {
jTextArea1.append("TA "+iMessage.dateString+"
"+iMessage.timeString+"\n"+iMessage.messString+"\n\n");
}
}
@SuppressWarnings()
private void initComponents() {
jCheckBox1 = new javax.swing.JCheckBox();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
jButton2 = new javax.swing.JButton();
jFormattedTextField1 = new javax.swing.JFormattedTextField();
jFormattedTextField2 = new javax.swing.JFormattedTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
JAVA语言,聊天室实验报告
jPanel3 = new javax.swing.JPanel();
jComboBox1 = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jCheckBox1.setText("jCheckBox1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(255, 255, 255));
setBounds(new java.awt.Rectangle(0, 0, 520, 520));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setModalExclusionType(java.awt.Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
jTextArea2.setColumns(20);
jTextArea2.setFont(new java.awt.Font("微软雅黑", 0, 14)); // NOI18N jTextArea2.setLineWrap(true);
jTextArea2.setRows(5);
jScrollPane2.setViewportView(jTextArea2);
jButton2.setText(" 发送 ");
jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt);
}
});
jFormattedTextField1.setText("127.0.0.1");
jFormattedTextField1.setToolTipText("");
jFormattedTextField2.setText("5200");
jFormattedTextField2.setToolTipText("");
jLabel1.setText("IP:");
jLabel2.setText(":");
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "127.0.0.1", "172.16.202.19", "172.18.254.216" }));
jComboBox1.addItemListener(new java.awt.event.ItemListener() {
JAVA语言,聊天室实验报告
public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBox1ItemStateChanged(evt);
}
});
jLabel3.setText("对方IP:");
jLabel3.setToolTipText("");
javax.swing.GroupLayout jPanel3Layout = new
javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addPreferredGap(ponentPlacement.UNRELATED)
.addComponent(jComboBox1,
javax.swing.GroupLayout.PREFERRED_SIZE, 131,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox1,
javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
JAVA语言,聊天室实验报告
jTextArea1.setFont(new java.awt.Font("微软雅黑", 0, 14)); // NOI18N jTextArea1.setLineWrap(true);
jTextArea1.setRows(5);
jScrollPane3.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jLabel1)
.addPreferredGap(ponentPlacement.RELATED)
.addComponent(jFormattedTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE, 104,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ponentPlacement.RELATED)
.addComponent(jLabel2,
javax.swing.GroupLayout.PREFERRED_SIZE, 6,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ponentPlacement.RELATED)
.addComponent(jFormattedTextField2,
javax.swing.GroupLayout.PREFERRED_SIZE, 43,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ponentPlacement.RELATED, 123, Short.MAX_VALUE)
.addComponent(jButton2))
.addComponent(jScrollPane2)
.addComponent(jScrollPane3))
.addPreferredGap(ponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
JAVA语言,聊天室实验报告
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel3,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane3,
javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE))
.addPreferredGap(ponentPlacement.RELATED)
.addComponent(jScrollPane2,
javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
.addPreferredGap(ponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jFormattedTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jFormattedTextField2,
javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addGap(2, 2, 2))
);
pack();
}// </editor-fold>
addMessage(chatIpAddress, jTextArea2.getText(), true);
jTextArea2.setText("");
}
if(evt.getStateChange() == 1) {
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
JAVA语言,聊天室实验报告
chatIpAddress = evt.getItem().toString();
reChatWindow(chatIpAddress);
}
}
private Point ;
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TalkHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TalkHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TalkHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TalkHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TalkHome().setVisible(true);
}
});
JAVA语言,聊天室实验报告
}
// Variables declaration - do not modify
private javax.swing.JButton jButton2;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JFormattedTextField jFormattedTextField1;
private javax.swing.JFormattedTextField jFormattedTextField2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
}
class IMessage {
public boolean ismyself;
public String messString;
public String dateString, timeString;
public IMessage(String mess, boolean ismyself) {
this.ismyself = ismyself;
this.messString = mess;
this.dateString = DateFormat.getDateInstance().format(new Date()); this.timeString = DateFormat.getTimeInstance().format(new Date()); }
}
四、实验心得
其实java已经将TCP和UDP协议高度封装了,熟练使用ServerSocket和Socket,DataGram会写出想要的网络程序,并不是很难。实验中遇到的问题有传送过来的数据显示成乱码,是因为编码的问题。
正在阅读:
聊天程序设计实验报告06-10
婚后20年,凤凰老公的真面目让我胆寒08-02
放飞小鸟作文500字07-06
2017-2018九年级英语第一学期中期考试 12-04
豆腐花作文500字07-05
政府推进节能减排的措施课程考试 96分06-06
HSE监理细则03-18
民事诉讼法(2009.7新)04-29
水果玉米大棚种植示范基地项目可行性研究报告-中投信德06-23
变更管理制度12-12
- 教学能力大赛决赛获奖-教学实施报告-(完整图文版)
- 互联网+数据中心行业分析报告
- 2017上海杨浦区高三一模数学试题及答案
- 招商部差旅接待管理制度(4-25)
- 学生游玩安全注意事项
- 学生信息管理系统(文档模板供参考)
- 叉车门架有限元分析及系统设计
- 2014帮助残疾人志愿者服务情况记录
- 叶绿体中色素的提取和分离实验
- 中国食物成分表2020年最新权威完整改进版
- 推动国土资源领域生态文明建设
- 给水管道冲洗和消毒记录
- 计算机软件专业自我评价
- 高中数学必修1-5知识点归纳
- 2018-2022年中国第五代移动通信技术(5G)产业深度分析及发展前景研究报告发展趋势(目录)
- 生产车间巡查制度
- 2018版中国光热发电行业深度研究报告目录
- (通用)2019年中考数学总复习 第一章 第四节 数的开方与二次根式课件
- 2017_2018学年高中语文第二单元第4课说数课件粤教版
- 上市新药Lumateperone(卢美哌隆)合成检索总结报告
- 程序设计
- 实验
- 聊天
- 报告
- 自考《社会学概论》复习资料整理
- 泉州市出口退税业务培训试卷
- 2016生物中考知识点整合
- 三相异步电机定子绕线方法
- 2012年深圳市中考语文试卷1
- 股票质押业务交流与分享201511
- 毕业论文_基于QT的嵌入式电子相册
- 美术教学案例与分析
- 干部在线学习“喜迎十八大”知识竞赛试题_答案
- 矿山电工学复习题
- 2015机械制图试题及参考答案(一)
- 语文S版四年级语文下册期末综合复习水平练习
- 财产保险公司中支筹建方案
- 施工电梯附着、加节方案
- 2021年语文版四年级语文下册期末试卷训练及答案
- 油液电瓶轮胎基础知识
- 3dmax5.X常用快捷键
- 接近开关可行性研究分析报告-甲级资质
- 第7章算法程序与计算系统之灵魂练习题答案解析
- 招商证券-保险公司研究图谱第二卷:保险公司总是缺资本金吗