java聊天服务器加客户列表代码的简单介绍
admin 发布:2022-12-19 16:31 146
今天给各位分享java聊天服务器加客户列表代码的知识,其中也会对进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:
- 1、用JAVA编写一个客户机服务器聊天程序
- 2、高手进,java实现聊天功能?
- 3、速求用JAVA语言写聊天室的源代码
- 4、java socket,我有客户端和服务器的代码,帮我添加广播和能多人会话,加分!!代码如下
用JAVA编写一个客户机服务器聊天程序
服务器端(注意要先启动服务器端)
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class server extends Frame implements ActionListener {
Label label = new Label("交谈内容");
Panel panel = new Panel();
TextField tf = new TextField(10);
TextArea ta = new TextArea();
ServerSocket server;
Socket client;
InputStream in;
OutputStream out;
public server() {
super("服务器");
setSize(250, 250);
panel.add(label);
panel.add(tf);
tf.addActionListener(this);
add("North", panel);
add("Center", ta);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
show();
try {
server = new ServerSocket(4000);
client = server.accept();
ta.append("客户机是:" + client.getInetAddress().getHostName() + "\n\n");
in =client.getInputStream();
out= client.getOutputStream();
} catch (IOException ioe) {
}
while (true) {
try {
byte[] buf = new byte[256];
in.read(buf);
String str = new String(buf);
ta.append("客户机说:" + str + "\n\n");
} catch (IOException e) {
}
}
}
public void actionPerformed(ActionEvent e) {
try {
String str = tf.getText();
byte[] buf = str.getBytes();
tf.setText(null);
out.write(buf);
ta.append("我说:" + str + "\n");
} catch (IOException ioe) {
}
}
public static void main(String[] args) {
new server();
}
}
客户端
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class client extends Frame implements ActionListener {
Label label = new Label("交谈内容");
Panel panel = new Panel();
TextField tf = new TextField(10);
TextArea ta = new TextArea();
Socket client;
InputStream in;
OutputStream out;
public client() {
super("客户机");
setSize(250, 250);
panel.add(label);
panel.add(tf);
tf.addActionListener(this);
add("North", panel);
add("Center", ta);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
show();
try {
client = new Socket(InetAddress.getLocalHost(), 4000);
ta.append("服务器是:" + client.getInetAddress().getHostName() + "\n\n");
in = client.getInputStream();
out = client.getOutputStream();
} catch (IOException ioe) {
}
while (true) {
try {
byte[] buf = new byte[256];
in.read(buf);
String str = new String(buf);
ta.append("服务器说:" + str + "\n");
} catch (IOException e) {
}
}
}
public void actionPerformed(ActionEvent e) {
try {
String str = tf.getText();
byte[] buf = str.getBytes();
tf.setText(null);
out.write(buf);
ta.append("我说:" + str + "\n");
} catch (IOException iOE) {
}
}
public static void main(String args[]) {
new client();
}
}
这个只能在自己一台电脑上先启动服务器再启动客户端才行,要想一台机子启动服务器端一台机子启动客户端需要把客户端的 client = new Socket(InetAddress.getLocalHost(), 4000);改成 client = new Socket("服务器Ip", 4000);(前提是两台机子连在局域网里面的)
高手进,java实现聊天功能?
。。。这个我以前也遇到过、不过我是用C#写的、不过后来也有java的、你可以、使用Swing做的简单界面,及使用Socket套接字实现简单聊天 。。。。。。但是、我不知道你问的是C/S模式还是B/S 模式?
其中、B/S模式可以用Servlet来实现,思路是通过Context上下文绑定参数实现
而C/S模式的,是通过RMI远程调用的方法实现的。。。先给你个C/S模式的核心代码。。。import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;public class Server extends JFrame
{
public static void main(String [] args)
{
Server server=new Server();
//设定框架的关闭方式
server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//显示框架
server.setVisible(true);
server.pack();
CreateServer cs=new CreateServer(server);
}
// 设定框架的宽度和高度
private static final int WIDTH=450;
private static final int HEIGHT=450;
// 聊天信息框
JTextArea mainArea=new JTextArea(12,35);
// 发送信息的填写框
JTextArea sendArea=new JTextArea(5,30);
// 构造函数
public Server()
{
//定位框架
Toolkit kit=Toolkit.getDefaultToolkit();
Dimension screenSize=kit.getScreenSize();//获取电脑当前分辨率
int width=screenSize.width;
int height=screenSize.height;
int x=(width-WIDTH)/2;
int y=(height-HEIGHT)/2;
//设置窗口显示位置
setLocation(x,y);
//设置框架大小
setSize(WIDTH,HEIGHT);
//设置标题
setTitle("小新新聊天服务器");
//设置窗口的自定义大小
setResizable(false);
//在内容表格上创建3个面板并加入到内容表格
Container con=this.getContentPane();
JPanel labelPanel=new LabelPanel();
con.add(labelPanel,BorderLayout.NORTH);
JPanel contentPanel=new ContentPanel();
con.add(contentPanel,BorderLayout.CENTER);
JPanel sendPanel=new SendPanel();
con.add(sendPanel,BorderLayout.SOUTH);
}
//聊天窗口的标题面板
class LabelPanel extends JPanel
{
public LabelPanel()
{
Font font=new Font("Dialog",Font.BOLD,18);
JLabel label=new JLabel("欢迎使用小新新聊天服务器");
label.setFont(font);
this.add(label);
}
}
// 聊天信息查看面板
//该面板内的区域为不可编辑区域
class ContentPanel extends JPanel
{
public ContentPanel()
{
FlowLayout fl=new FlowLayout(FlowLayout.CENTER);
this.setLayout(fl);
mainArea.setLineWrap(true);
mainArea.setEditable(false);
JScrollPane scrollPanel=new JScrollPane(mainArea);
this.add(scrollPanel);
}
}
// 填写发送信息的面板
class SendPanel extends JPanel
{
public SendPanel()
{
//面板的组件之间水平分隔15像素,垂直间距10像素
FlowLayout layout=new FlowLayout(FlowLayout.LEFT,15,10);
this.setLayout(layout);
sendArea.setLineWrap(true);
JScrollPane scrollPanel=new JScrollPane(sendArea);
this.add(scrollPanel);
JButton send=new JButton("发送");
this.add(send);
//对发送按钮注册动作监听器
send.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String msg=sendArea.getText();
if(!msg.equals(""))
{
mainArea.append("【服务器】:"+msg+"\n");
sendArea.setText("");
CreateServer.sendMsg(msg);
}
else
{
return;
}
}
});
}
}
}
//创建服务器ServerSocket的类
class CreateServer extends Thread
{
private Server server;
private static BufferedReader in=null;//存储客户端发送到服务器的数据
private static PrintWriter out=null;//存储服务器发送到客户端的数据
private Socket socket=null;//等待客户端连接socket
private ServerSocket ss=null;//开启服务器socket连接
//构造函数
public CreateServer(Server s)
{
this.server=s;
try
{
ss=new ServerSocket(2345);
System.out.println("服务器成功启动...!");
socket=ss.accept();//等待客户端请求
//获取输入到服务器的数据
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//获取输出到客户端的数据
out=new PrintWriter(socket.getOutputStream(),true);
out.println("你好!");
}
catch(Exception r)
{
r.printStackTrace();
}
this.start();//启动线程
}
//实现信息发送到客户端的发送方法
public static void sendMsg(String s)
{
try
{
out.println("【服务器】:"+s+"\n");
}
catch(Exception e)
{
System.out.println("发送信息失败...!!");
e.printStackTrace();
}
}
// 线程Thread类的run方法实现对客户端发送来的数据监听
//线程启动后开始该方法,执行线程体
public void run()
{
String msg="";
while(true)
{
try
{
msg=in.readLine();
//Thread.sleep(500);//线程睡眠
}
catch (SocketException ex)
{
ex.printStackTrace();
break;
}
catch(IOException r)
{
r.printStackTrace();
break;
}
//若从客户端获取的信息不为空对象也不为空串
//则把信息显示在聊天信息文本域
if(msg!=null msg.trim()!="")
{
server.mainArea.append(msg+"\n");
}
}
}
}
速求用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; i response.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; i response.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; i response.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 socket,我有客户端和服务器的代码,帮我添加广播和能多人会话,加分!!代码如下
根据你的改了个!不好意思,其中读写的思路稍微有点不同!不过可以做参考!
Server端代码:
import java.net.*;
import java.io.*;
import java.util.*;
public class TestServer {
ServerSocket s = null;
boolean started = false;//用来监听服务器是否启动!
ListServerReaderWriter clients = new ArrayListServerReaderWriter();//用来存放启动的客服端
public static void main(String[] args) {
new TestServer().start();
}
public void start() {
try {
s = new ServerSocket(5050);
started = true;
} catch(SocketException e) {
System.out.println("5050端口正在使用中!!!请关掉相关程序并重新运行服务器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
int i = 1;
try {
while(started) {
Socket ss = s.accept();
ServerReaderWriter c = new ServerReaderWriter(ss);//建立客服端
System.out.println("第" + i + "个客服端启动!");
++i;
new Thread(c).start();//启动线程
clients.add(c);
}
} catch (EOFException e) {
System.out.println("客服端被关闭!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerReaderWriter implements Runnable { //建议使用Runnable避免你重写run方法麻烦!
private Socket s;
private DataInputStream dis = null;//注意赋值,养成好习惯!
private DataOutputStream dos = null;
private boolean bConnected = false;//用于调用连接成功后的run方法
public ServerReaderWriter(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("有客户退出!");
}
}
public void run() {
try {
while (bConnected) {
String input = dis.readUTF();
System.out.println(input);
for(int i=0; iclients.size(); ++i) {
ServerReaderWriter c = clients.get(i);
c.send(input);
}
}
} catch(SocketException e) {
System.out.println("一个客服端已关闭,请勿再像他发送信息!");
} catch (EOFException e) {
System.out.println("谢谢使用!");
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null) {
dis.close();
}
if (dos != null) {
dos.close();
}
if (s != null) {
s.close();
s = null;
}
//clients.clear();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
Client端代码:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class TestClient extends Frame { //用到Frame生产界面比较直观
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfText = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new ClientReaderWriter());
public static void main(String[] args){
new TestClient().launchFrame();
}
public void launchFrame() {
this.setSize(300, 300); //设置客服端窗口格式
this.setLocation(400, 300);
add(tfText, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
this.pack();
this.addWindowListener(new WindowAdapter() { //监听窗口关闭事件
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfText.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 5050); //依据自己的服务器,我这里用的localhost
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("连接服务器!");
bConnected = true;
} catch(ConnectException e) {
System.out.println("请检查服务器是否启动!");
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.exit(0);
}
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();
}
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfText.getText().trim();
tfText.setText("");
try {
dos.writeUTF(str);
if(str.equals("bye")){
System.exit(0);
}
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
class ClientReaderWriter implements Runnable {
public void run() {
try {
while(bConnected) {
String input = dis.readUTF();
taContent.setText(taContent.getText() + input +'\n');
}
} catch (SocketException e) {
System.out.println("轻轻的我走了!Bye-bye!");
} catch (EOFException e) {
System.out.println("我断网了,再见!");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
java聊天服务器加客户列表代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于、java聊天服务器加客户列表代码的信息别忘了在本站进行查找喔。
版权说明:如非注明,本站文章均为 AH站长 原创,转载请注明出处和附带本文链接;
相关推荐
- 05-19网络推广怎么找客户资源,怎么在网络推广
- 05-18免费个人网站空间,国外免费网站域名服务器查询
- 05-18新手怎么做网络销售,网销怎么找客户资源
- 05-17怎么创建网址,怎么创建网址聊天
- 05-17做公司网页,做公司网页有什么简单的方法
- 05-16贷款客户大数据精准获客,信贷员10大获客软件
- 05-14深圳网站seo,深圳网站服务器托管
- 05-13网销怎么找客户资源,做销售怎么和客户聊天
- 05-12深圳seo公司的简单介绍
- 05-11设计一个简单的网页,独立站建站平台有哪些
取消回复欢迎 你 发表评论:
- 标签列表
- 最近发表
- 友情链接