用JAVA如何实现GUI的聊天室?只需实现基本的聊天室功能即可 。希望给出服务器源代码和客户端源代码 。转自 Ian Darwin's Java Cookbook,
用的是Socket通信AWT实现GUI 。
Code比较长,这里贴不下,可以去下面URL直接下载 。
定义常量
Server端
Client端
java聊天室 源代码【ClientSocketDemo.java 客户端Java源代码】
import java.net.*;
import java.io.*;
public class ClientSocketDemo
{
//声明客户端Socket对象socket
Socket socket = null;
//声明客户器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明字符串数组对象response,用于存储从服务器接收到的信息
String response[];
//执行过程中,没有参数时的构造方法,本地服务器在本地,取默认端口10745
public ClientSocketDemo()
{
try
{
//创建客户端socket,服务器地址取本地,端口号为10745
socket = new Socket("localhost",10745);
//创建客户端数据输入输出流,用于对服务器端发送或接收数据
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//获取客户端地址及端口号
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
//向服务器发送数据
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
//从服务器接收数据
response = new String[3];
for (int i = 0; iresponse.length; i)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中,有一个参数时的构造方法,参数指定服务器地址,取默认端口10745
public ClientSocketDemo(String hostname)
{
try
{
//创建客户端socket,hostname参数指定服务器地址,端口号为10745
socket = new Socket(hostname,10745);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; iresponse.length; i)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中,有两个个参数时的构造方法 , 第一个参数hostname指定服务器地址
//第一个参数serverPort指定服务器端口号
public ClientSocketDemo(String hostname,String serverPort)
{
try
{
socket = new Socket(hostname,Integer.parseInt(serverPort));
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; iresponse.length; i)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
String comd[] = args;
if(comd.length == 0)
{
System.out.println("Use localhost(127.0.0.1) and default port");
ClientSocketDemo demo = new ClientSocketDemo();
}
else if(comd.length == 1)
{
System.out.println("Use default port");
ClientSocketDemo demo = new ClientSocketDemo(args[0]);
}
else if(comd.length == 2)
{
System.out.println("Hostname and port are named by user");
ClientSocketDemo demo = new ClientSocketDemo(args[0],args[1]);
}
else System.out.println("ERROR");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
【ServerSocketDemo.java 服务器端Java源代码】
import java.net.*;
import java.io.*;
public class ServerSocketDemo
{
//声明ServerSocket类对象
ServerSocket serverSocket;
//声明并初始化服务器端监听端口号常量
public static final int PORT = 10745;
//声明服务器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明InetAddress类对象ip,用于获取服务器地址及端口号等信息
InetAddress ip = null;
//声明字符串数组对象request,用于存储从客户端发送来的信息
String request[];
public ServerSocketDemo()
{
request = new String[3]; //初始化字符串数组
try
{
//获取本地服务器地址信息
ip = InetAddress.getLocalHost();
//以PORT为服务端口号 , 创建serverSocket对象以监听该端口上的连接
serverSocket = new ServerSocket(PORT);
//创建Socket类的对象socket , 用于保存连接到服务器的客户端socket对象
Socket socket = serverSocket.accept();
System.out.println("This is server:" String.valueOf(ip) PORT);
//创建服务器端数据输入输出流 , 用于对客户端接收或发送数据
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//接收客户端发送来的数据信息 , 并显示
request[0] = in.readUTF();
request[1] = in.readUTF();
request[2] = in.readUTF();
System.out.println("Received messages form client is:");
System.out.println(request[0]);
System.out.println(request[1]);
System.out.println(request[2]);
//向客户端发送数据
out.writeUTF("Hello client!");
out.writeUTF("Your ip is:" request[1]);
out.writeUTF("Your port is:" request[2]);
}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
ServerSocketDemo demo = new ServerSocketDemo();
}
}
JAVA聊天室 客户端 和 服务器 完整代码CS模式的QQ这是服务器:ChatServer.javaimport java.net.*;
import java.io.*;
public class ChatServer
{
final static int thePort=8189;
ServerSocket theServer;
ChatHandler[] chatters;
int numbers=0;
public static void main(String args[])
{
ChatServer app=new ChatServer();
app.run();
}
public ChatServer()
{
try
{
theServer=new ServerSocket(thePort);
chatters=new ChatHandler[10];
}
catch(IOException io){}
}
public void run()
{
try
{
System.out.println("服务器已经建立java聊天室gui代码!");
while(numbers10)
{
Socket theSocket=theServer.accept();
ChatHandler chatHandler=new ChatHandler(theSocket,this);
chatters[numbers]=chatHandler;
numbers;
}
}catch(IOException io){}
}
public synchronized void removeConnectionList(ChatHandler c)
{
int index=0;
for(int i=0;i=numbers-1;i)
if(chatters[i]==c)index=i;
for(int i=index;inumbers-1;i)
chatters[i]=chatters[i 1];
chatters[numbers-1]=null;
numbers--;
}
public synchronized String returnUsernameList()
{
String line="";
for(int i=0;i=numbers-1;i)
line=line chatters[i].user ":";
return line;
}
public void broadcastMessage(String line)
{
System.out.println("发布信息:" line);
for(int i=0;i=numbers-1;i)
chatters[i].sendMessage(line);
}
}====================================================这是客户端java聊天室gui代码:ChatClient.javaimport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ChatClient extends Thread implements ActionListener
{
JTextField messageField,IDField,ipField,portField;
JTextArea message,users;
JButton connect,disconnect;
String user="";
String userList[]=new String[10];
Socket theSocket;
BufferedReader in;
PrintWriter out;
boolean connected=false;
Thread thread;
public static void main(String args[])
{
JFrame frame=new JFrame("聊天室");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ChatClient cc=new ChatClient();
JPanel content=cc.createComponents();
frame.getContentPane().add(content);
frame.setSize(550,310);
frame.setVisible(true);
}
public JPanel createComponents()
{
JPanel pane=new JPanel(new BorderLayout());
message=new JTextArea(10,35);
message.setEditable(false);
JPanel paneMsg=new JPanel();
paneMsg.setBorder(BorderFactory.createTitledBorder("聊天内容"));
paneMsg.add(message);
users=new JTextArea(10,10);
JPanel listPanel=new JPanel();
listPanel.setBorder(BorderFactory.createTitledBorder("在线用户:"));
listPanel.add(users);
messageField=new JTextField(50);
IDField=new JTextField(5);
ipField=new JTextField("LocalHost");
portField=new JTextField("8189");
connect=new JButton("连 接");
disconnect=new JButton("断 开");
disconnect.setEnabled(false);
JPanel buttonPanel=new JPanel();
buttonPanel.add(new Label("服务器IP:"));
buttonPanel.add(ipField);
buttonPanel.add(new Label("端口:"));buttonPanel.add(portField);
buttonPanel.add(new Label("用户名:"));
buttonPanel.add(IDField);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
pane.add(messageField,"South");
pane.add(buttonPanel,"North");
pane.add(paneMsg,"Center");
pane.add(listPanel,"West");
connect.addActionListener(this);
disconnect.addActionListener(this);
messageField.addActionListener(this);
IDField.addActionListener(this);
ipField.addActionListener(this);
return pane;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==connect){
user=IDField.getText();
String ip=ipField.getText();
int port =Integer.parseInt(portField.getText());
if(!user.equals("")connectToServer(ip,port,user))
{
disconnect.setEnabled(true);
connect.setEnabled(false);
}
}
if(e.getSource()==disconnect)disconnectFromServer();
if(e.getSource()==messageField)
if(theSocket!=null)
{
out.println("MESSAGE:" messageField.getText());
messageField.setText("");
}
}
public void disconnectFromServer()
{
if(theSocket!=null)
{
try
{
connected=false;
out.println("LEAVE:" user);
disconnect.setEnabled(false);
connect.setEnabled(true);
thread=null;
theSocket.close();
}catch(IOException io){}
theSocket=null;
message.setText("");
users.setText("");
}
}
public boolean connectToServer(String ip,int port,String ID)
{
if(theSocket!=null)
return false;
try
{
theSocket=new Socket(ip,port);
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
out.println("USER:" user);
message.setText("");
connected=true;
thread=new Thread(this);
thread.start();
}catch(Exception e){return false;}
return true;
}
public void extractMessage(String line)
{
System.out.println(line);
Message messageline;
messageline=new Message(line);
if(messageline.isValid())
{
if(messageline.getType().equals("JOIN"))
{
user=messageline.getBody();
message.append(user "进入java聊天室gui代码了聊天室\n");
}
else if(messageline.getType().equals("LIST"))
updateList(messageline.getBody());
else if(messageline.getType().equals("MESSAGE"))
message.append(messageline.getBody() "\n");
else if(messageline.getType().equals("REMOVE"))
message.append(messageline.getBody() "离开了聊天室\n");
}
else
message.append("出现问题:" line "\n");
}
public void updateList(String line)
{
users.setText("");
String str=line;
for(int i=0;i10;i)
userList[i]="";
int index=str.indexOf(":");
int a=0;
while(index!=-1){
userList[a]=str.substring(0,index);
str=str.substring(index 1);
a;
index=str.indexOf(":");
}
for(int i=0;i10;i)
users.append(userList[i] "\n");
}
public void run(){
try{
String line="";
while(connectedline!=null){
line=in.readLine();
if(line!=null) extractMessage(line);
}
}catch(IOException e){}
}
} =======================================================import java.net.*;
import java.io.*;
class ChatHandler extends Thread{
Socket theSocket;
BufferedReader in;
PrintWriter out;
int thePort;
ChatServer parent;
String user="";
boolean disconnect=false;
public ChatHandler(Socket socket,ChatServer parent){
try{
theSocket=socket;
this.parent=parent;
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
thePort=theSocket.getPort();
start();
}catch(IOException io){}
}
public void sendMessage(String line){
out.println(line);
}
public void setupUserName(String setname){
user=setname;
//System.out.print(user "参加");
parent.broadcastMessage("JOIN:" user);
}
public void extractMessage(String line){
Message messageline;
messageline = new Message(line);
if(messageline.isValid()){
if(messageline.getType().equals("USER")){
setupUserName(messageline.getBody());
parent.broadcastMessage("LIST:" parent.returnUsernameList());
}
else if(messageline.getType().equals("MESSAGE")){
parent.broadcastMessage("MESSAGE:" user "说: " messageline.getBody());
}
else if(messageline.getType().equals("LEAVE")){
String c=disconnectClient();
parent.broadcastMessage("REMOVE:" c);
parent.broadcastMessage("LIST:" parent.returnUsernameList());
}
}
else
sendMessage("命令不存在!");
}
public String disconnectClient(){
try{
in.close();
out.close();
theSocket.close();
parent.removeConnectionList(this);
disconnect=true;
}catch(Exception ex){}
return user;
}
public void run(){
String line,name;
boolean valid=false;
try{
while((line=in.readLine())!=null){
System.out.println("收到:" line);
extractMessage(line);
}
}catch(IOException io){}
}
}
=========================================================
Message.javapublic class Message{
private String type;
private String body;
private boolean valid;
public Message(String messageLine){
valid=false;
type=body=null;
int pos=messageLine.indexOf(":");
if(pos=0){
type=messageLine.substring(0,pos).toUpperCase();
body=messageLine.substring(pos 1);
valid=true;
}
}
public Message(String type,String body){
valid=true;
this.type=type;
this.body=body;
}
public String getType(){
return type;
}
public String getBody(){
return body;
}
public boolean isValid(){
return valid;
}
} ==================================================共有4个文件 , 先运行服务段端 。。。这是java聊天室gui代码我以前学的时候写过的!希望能帮的上你
编写一个java GUI程序(其实帮我改改)把frame=new subJFrame("DrawShapes");改成frame=new JFrame("DrawShapes");
程序基本没问题,在public void paint(Graphics g)中加上如下程序就可以了 。
public void paint(Graphics g){
switch(i){
【java聊天室gui代码 java实现聊天室功能包含全部代码,有界面】case 1: g.drawOval(20,20,40,40);break;
case 2: g.drawRect(20,20,40,40);break;
case 3: g.drawOval(20,30,40,50);break;
case 4: g.drawLine(20,20,40,40);break;
}
}
用java编写多人聊天室程序,不需要太复杂求大神发给我,最好能运行 , 有源代码 。谢谢了文件1:
package com.qq;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.Date;
public class Server {
public Server() {
try {
ServerSocket s = new ServerSocket(8888);
Socket ss = s.accept();
OutputStream out = ss.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
InputStream in = ss.getInputStream();
DataInputStream din = new DataInputStream(in);
System.out.print(din.readUTF()"!");
dout.writeUTF("你已经连接到服务器""\t""你的地址:"ss.getInetAddress()
"\t""你的链接端口:"ss.getLocalPort()"\n");
new ReadMessage(din).start();
new SendMessage(dout).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Server();
}
}
// 接受客户端信息
class ReadMessage extends Thread {
private DataInputStream din;
public ReadMessage(DataInputStream din) {
this.din = din;
}
public void run() {
String str;
try {
while (true) {
str = din.readUTF();
System.out.println(new Date().toLocaleString()"客户端说:"str);
if (str.equals("bye")) {
System.out.println("客户端下线!");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 发出服务器信息
class SendMessage extends Thread {
private DataOutputStream dout;
public SendMessage(DataOutputStream dout) {
this.dout = dout;
}
public void run() {
InputStreamReader inr = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(inr);
String str;
try {
while (true) {
str = buf.readLine();
dout.writeUTF(str);
if (str.equals("bye")) {
System.out.println("服务器退出!");
System.exit(1);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
----------------------------------------
文件2:
package com.qq;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.Socket;
import java.io.IOException;
import java.util.Date;
public class Client {
public Client() {
try {
Socket s = new Socket("192.168.1.2", 8888);
InputStream in = s.getInputStream();
DataInputStream din = new DataInputStream(in);
OutputStream out = s.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF("服务器你好!我是客户端");
System.out.println(din.readUTF());
new Thread(new SenderMessage(dout)).start();
new Thread(new ReaderMessage(din)).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Client();
}
}
class ReaderMessage implements Runnable {
private DataInputStream din;
public ReaderMessage(DataInputStream din) {
this.din = din;
}
public void run() {
String str;
try {
while (true) {
str = din.readUTF();
System.out.println(new Date().toLocaleString()"服务器说:"str);
if (str.equals("bye")) {
System.out.println("服务器已经关闭,此程序自动退出!");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class SenderMessage implements Runnable {
private DataOutputStream dout;
public SenderMessage(DataOutputStream dout) {
this.dout = dout;
}
public void run() {
String str;
InputStreamReader inf = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(inf);
try {
while (true) {
str = buf.readLine();
dout.writeUTF(str);
if (str.equals("bye")) {
System.out.println("客户端自己退出!");
System.exit(1);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
java实现聊天室是怎么做到的?Java 实现聊天室可以分为以下几个步骤:
建立服务器端
首先需要建立一个服务器端,负责接收客户端的连接请求并处理客户端发送过来的消息 。
建立客户端
然后需要建立客户端,客户端通过网络连接到服务器端 , 并向服务器端发送消息 。
实现通信协议
为了实现聊天室功能 , 需要定义一个通信协议,规定客户端和服务器端之间的通信格式,例如消息的头部和内容等 。
实现多线程处理
聊天室通常会有多个用户同时在线,因此需要使用多线程来处理多个客户端的连接请求和消息传递 。
实现GUI界面(可?。?
为了方便用户使用,可以实现一个GUI界面,让用户可以方便地发送和接收消息 。
以下是一个简单的 Java 聊天室的代码示例:
java
Copy code
// 服务器端代码
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
Socket socket = serverSocket.accept();
new Thread(new ServerThread(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread implements Runnable {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
public ServerThread(Socket socket) {
this.socket = socket;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String msg;
while ((msg = reader.readLine()) != null) {
// 处理客户端发送过来的消息
System.out.println("接收到消息:"msg);
// 将消息发送给所有客户端
for (Socket s : ServerThreadList.getList()) {
if (s != socket) {
PrintWriter w = new PrintWriter(s.getOutputStream());
w.println(msg);
w.flush();
}
}
}
// 关闭连接
socket.close();
ServerThreadList.removeThread(this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThreadList {
private static List
list = new ArrayList();
public static void addThread(ServerThread thread) {
list.add(thread);
}
public static void removeThread(ServerThread thread) {
list.remove(thread);
}
public static List
getList() {
return list;
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
new Thread(new ClientThread(socket)).start();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
while (true) {
String msg = reader.readLine();
writer.println(msg);
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader reader;
public ClientThread(Socket socket) {
this.socket = socket;
try {
reader
关于java聊天室gui代码和java实现聊天室功能包含全部代码,有界面的介绍到此就结束了 , 不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。
推荐阅读
- centos虚拟机没有ip,centos虚拟机没有网卡
- java代码继承的例子,java代码继承的例子有哪些
- cad用什么配置电脑,cad用什么配置电脑比较好
- gis无法修改范围,arcgis无法编辑字段
- 小程序php传到数据库 小程序对接php接口接收数据
- go语言实现,Go语言实现Crond定时任务的示例
- 如何让ppt段落间距舒服,ppt设置段落间距
- 揭秘直播的技巧,揭秘直播的技巧和方法
- mysql分区怎么用 mysql57分区表