您的位置:首页 > 其它

也算是终于把局域网多人聊天室写好了

2015-12-07 00:00 447 查看
摘要: 一开始在命令行调试的,总不对,后来用了两台电脑来调试,也算是终于弄好了.很简单的聊天室.

首先是服务端

package com.zhong.Thread;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Serverthread {

static ArrayList<Socket> list = new ArrayList<Socket>();

public static void main(String args[]){
ServerSocket sos = null;

try {
sos = new ServerSocket(5566);
int i =0;
while(true){
Socket s = sos.accept();
list.add(s);
i++;
System.out.println("第"+i+"号客户机连接到服务器!");
ClientThread sst = new ClientThread(s,list,i);
Thread th = new Thread(sst);
th.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientThread implements Runnable{
private Socket soc;
private ArrayList<Socket> list = null;
private int i;

public ClientThread(Socket soc,ArrayList<Socket> list,int i){
this.soc = soc;
this.list = list;
this.i = i;
}

@Override
public void run() {
// TODO Auto-generated method stub
PrintWriter out = null;
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader(
soc.getInputStream(),"utf-8"));
out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
soc.getOutputStream(),"utf-8")));
InetAddress id = soc.getInetAddress();
int p = soc.getPort();
String ss = "客户机ip地址:"+id+"端口号为:"+p;
System.out.println(ss);
out.println("欢迎客户机"+i+"加入多人聊天室");
out.flush();

while(true){
String str = in.readLine();
System.out.println("客户机"+i+"回复说:"+str);
String strbor = "客户机"+i+"说:"+str;
//byte b[] = strbor.getBytes();
for(int i = 0 ; i < list.size();i++){
Socket s = list.get(i);
if(s!=soc){
PrintWriter outer = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
s.getOutputStream(),"utf-8")));
outer.println(strbor);
outer.flush();
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out.close();
try {
soc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

然后是客户端

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.zhong.qq;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
*
* @author root
*/
public class QQChat extends javax.swing.JFrame {

/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Creates new form QQChat
*/
public QQChat() {
initComponents();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {

jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jt_history = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
jt_input = new javax.swing.JTextArea();
btn_send = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jButton4 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();

jButton1.setText("jButton1");

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(400, 500));

jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("多人聊天室");

jt_history.setEditable(false);
jt_history.setColumns(20);
jt_history.setRows(5);
jt_history.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jt_historyFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jt_historyFocusLost(evt);
}
});
jScrollPane1.setViewportView(jt_history);

jt_input.setColumns(20);
jt_input.setRows(5);
jt_input.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jt_inputFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jt_inputFocusLost(evt);
}
});
jt_input.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jt_inputKeyPressed(evt);
}
});
jScrollPane2.setViewportView(jt_input);

btn_send.setText("点击发送");
btn_send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_sendActionPerformed(evt);
}
});

jButton3.setText("清空输入内容");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});

jLabel2.setText("输入你想说的话");

jButton4.setText("清空聊天记录");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});

jLabel3.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
jLabel3MouseMoved(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(137, 137, 137))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
.addComponent(jButton3)
.addGap(44, 44, 44)
.addComponent(btn_send)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(68, 68, 68))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_send)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap())
);
this.setVisible(true);
pack();
InitSocket();

}// </editor-fold>

public void InitSocket(){

try {
socket = new Socket("192.168.1.111",5566);
jt_history.append("==============欢迎加入多人聊天室=============="+"\n");
in = new BufferedReader(
new InputStreamReader(
socket.getInputStream(),"utf-8"));
String str = in.readLine();
jt_history.append(str);
out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream(),"utf-8")));
while(true){
String ss = in.readLine();
jt_history.append(ss+"\n");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private void btn_sendActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String str,str1;
str = jt_input.getText().toString();
str1 = "[我说:]"+str+"\n";
jt_history.append(str1);
out.println(str);
out.flush();
jt_input.setText("");
}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jt_history.setText("");
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jt_input.setText("");
}

private void jLabel3MouseMoved(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}

private void jt_inputFocusGained(java.awt.event.FocusEvent evt) {
// TODO add your handling code here:
jLabel3.setText("正在输入...");
}

private void jt_inputFocusLost(java.awt.event.FocusEvent evt) {
// TODO add your handling code here:
jLabel3.setText("");
}

private void jt_historyFocusGained(java.awt.event.FocusEvent evt) {
// TODO add your handling code here:
jLabel3.setText("正在查看聊天记录...");
}

private void jt_historyFocusLost(java.awt.event.FocusEvent evt) {
// TODO add your handling code here:
jLabel3.setText("");
}

private void jt_inputKeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if(evt.isControlDown()){
jt_input.setText("");
}
}

/**
* @param args the command line arguments
*/
public static void main(String args[]){
new QQChat();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton btn_send;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jt_history;
private javax.swing.JTextArea jt_input;
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
// End of variables declaration
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  socket