⑴ 為java聊天室代碼加詳細注釋,並說明設計思路。好的加100分。
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;//引入包。
public class ChatClient {
public static void main(String[] args) {
ChatClient cc = new ChatClient();
cc.receive();
}
JTextField jtf; // 文本條
JTextArea jta; //文本域。
Socket s; //客戶端
PrintWriter out; //輸出流
BufferedReader in; //輸入流
public ChatClient() {
JFrame frame = new JFrame("ChatClient");//窗口
frame.setSize(400, 300); //大小
jta = new JTextArea(); //文本域
jta.setEditable(false); //不可編輯
jtf = new JTextField();//文件條
jtf.addActionListener(new ActionListener() { //添加監聽。
public void actionPerformed(ActionEvent arg0) {
send(); //調用send()方法
}
});
frame.getContentPane().add(new JScrollPane(jta)); //添加滾動條
frame.getContentPane().add(jtf, "South"); //添加文本條
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關閉窗口。
frame.setVisible(true); //可顯示的。
try {
s = new Socket("127.0.0.1", 9000); //連接服務端 socket("主機名",埠號);
in = new BufferedReader(new InputStreamReader(s.getInputStream())); //建立輸入流
out = new PrintWriter(s.getOutputStream());//輸出流
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void receive() { //接受服務端發來別的客戶端的信息。
while (true) {
try {
String text = in.readLine(); //讀一行
this.jta.append(text + "\n"); //jta 添加上讀入的。
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
}
}
public void send() { //發送消息
String text = this.jtf.getText(); //得到你輸入的消息
this.jtf.setText(""); //在文本域中顯示你輸入的消息。
out.println(text); //列印出。
out.flush(); //清空
}
}
Server端
import java.net.*;
import java.io.*;
import java.util.*;//引入包
public class ChatServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(9000); //建立服務端,埠號為9000
List list = new ArrayList(); //創建個List集合。
while (true) {
Socket s = ss.accept(); //等待客戶端的請求。
list.add(s); //把每一個client都add到集合中去。
Thread t = new ServerThread(s, list); //線程。
t.start(); //啟動。
}
}
}
class ServerThread extends Thread {
Socket s;
List list;
BufferedReader in;
PrintWriter out;
public ServerThread(Socket s, List list) { //構造。傳入socket和list。
this.s = s;
this.list = list;
try {
in = new BufferedReader(new InputStreamReader(s.getInputStream())); //輸入流
out = new PrintWriter(s.getOutputStream()); //輸出流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() { //必須實現其run()方法。
while (true) {
try {
String str = in.readLine(); //得到client端的message。
if (str == null) //如果沒有消息就返回。
return;
Iterator it = list.iterator(); //遍歷list。
while (it.hasNext()) { //如果list有下一個
Socket socket = (Socket) (it.next()); //因為list中都是存的socket
PrintWriter o = new PrintWriter(socket.getOutputStream()); //輸出流
o.println(str); //輸出
o.flush(); //清空
}
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
return;
}
}
}
}
⑵ 對下面的java代碼進行注釋,關鍵語句給點中文的解釋,部分函數的功能,這是個聊天室程序
package cn.text;
public class hah {
@Override
public String execute() throws Exception {
//轉換字元集
roomName = new String(roomName.getBytes("ISO-8859-1"),"utf-8");
System.out.println(roomName);
//轉換字元集
userName = new String(userName.getBytes("ISO-8859-1"),"utf-8");
System.out.println(userName);
//判斷房間是否為空
if(roomName==null){
System.out.println("你沒有選擇房間");
//設置返回提示的信息,在登錄頁面接受
setTip("你沒有選擇房間");
return "error";
}//判斷用戶是否為空
if(userName==null){
System.out.println("你沒有登陸");
setTip("你沒有登陸");
return "error";
}
//獲取session
Map session = ActionContext.getContext().getSession();
//將存在的用戶放入session
session.put("roomName", roomName);
//查看這個用戶當前是否在線
UserList test=userListService.getUserListsByUserName(userName);//即為在線用戶(半個小時內的發信息的用戶,由後台資料庫維護)
if(test==null){//不是在線用戶
System.out.println("歡迎您,"+userName+"聊天室名稱為:"+roomName);
//設置提示信息
setTip("歡迎您,"+userName+",聊天室名稱為:"+roomName);
//將用戶名 聊天室 當前聊天內容 當前聊天時間 放入 userListService實體類集合中
userListService.saveUserList(new UserList(roomName,userName,new java.sql.Timestamp(System.currentTimeMillis()),new java.sql.Timestamp(System.currentTimeMillis())));
//將時間放入session中
session.put("loginDate", new java.sql.Timestamp(System.currentTimeMillis()));
}else{
if(roomName.equals(test.getRoomName())){
setTip("您已經是該房間的在線用戶,可以繼續聊天!");
}else{
if(test.getRoomName()!=null&&!test.getRoomName().equals("")){
setTip("您進入了新的房間"+roomName+",上次進入的房間名稱為"+test.getRoomName());
}else{
setTip("您進入了新的房間"+roomName);
}
test.setRoomName(roomName);
//設置登錄時間
test.setLoginDate(new java.sql.Timestamp(System.currentTimeMillis()));
//設置離開時間
test.setMessDate(new java.sql.Timestamp(System.currentTimeMillis()));
//把這些信息放入集合中
userListService.updateUserList(test);
}
session.put("loginDate", test.getLoginDate());
}
//獲得當前該聊天室所有在線用戶
onlineUser=userListService.findOnlineUserLists(roomName);
//將在線用戶放入session
session.put("onlineUser", onlineUser);
return "success";
}
/**
* 下面這些代碼 是用工具生成的 ,你應該知道
* @return
*/
//UserListService 的get set 方法
public UserListService getUserListService() {
return userListService;
}
public void setUserListService(UserListService userListService) {
this.userListService = userListService;
}
//roomName 的get set 方法
public String getRoomName() {
return roomName;
}
public void setRoomName(String roomName) {
this.roomName = roomName;
}
//userName 的get set 方法
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
//onlineUser 的get set 方法
public List<String> getOnlineUser() {
return onlineUser;
}
public void setOnlineUser(List<String> onlineUser) {
this.onlineUser = onlineUser;
}
//messService 的get set 方法
public MessService getMessService() {
return messService;
}
public void setMessService(MessService messService) {
this.messService = messService;
}
//messStr 的get set 方法
public String getMessStr() {
return messStr;
}
public void setMessStr(String messStr) {
this.messStr = messStr;
}
}
⑶ 求java網路聊天室(B/S模式)程序代碼
共四個java文件,源代碼如下:
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.io.*;
import java.util.Hashtable;
public class ChatArea extends Panel implements ActionListener,Runnable
{
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread threadMessage=null;
TextArea 談話顯示區,私聊顯示區=null;
TextField 送出信息=null;
Button 確定,刷新談話區,刷新私聊區;
Label 提示條=null;
String name=null;
Hashtable listTable;
List listComponent=null;
Choice privateChatList;
int width,height;
public ChatArea(String name,Hashtable listTable,int width,int height)
{
setLayout(null);
setBackground(Color.orange);
this.width=width;
this.height=height;
setSize(width,height);
this.listTable=listTable;
this.name=name;
threadMessage=new Thread(this);
談話顯示區=new TextArea(10,10);
私聊顯示區=new TextArea(10,10);
確定=new Button("送出信息到:");
刷新談話區=new Button("刷新談話區");
刷新私聊區=new Button("刷新私聊區");
提示條=new Label("雙擊聊天者可私聊",Label.CENTER);
送出信息=new TextField(28);
確定.addActionListener(this);
送出信息.addActionListener(this);
刷新談話區.addActionListener(this);
刷新私聊區.addActionListener(this);
listComponent=new List();
listComponent.addActionListener(this);
privateChatList=new Choice();
privateChatList.add("大家(*)");
privateChatList.select(0);
add(談話顯示區);
談話顯示區.setBounds(10,10,(width-120)/2,(height-120));
add(私聊顯示區);
私聊顯示區.setBounds(10+(width-120)/2,10,(width-120)/2,(height-120));
add(listComponent);
listComponent.setBounds(10+(width-120),10,100,(height-160));
add(提示條);
提示條.setBounds(10+(width-120),10+(height-160),110,40);
Panel pSouth=new Panel();
pSouth.add(送出信息);
pSouth.add(確定);
pSouth.add(privateChatList);
pSouth.add(刷新談話區);
pSouth.add(刷新私聊區);
add(pSouth);
pSouth.setBounds(10,20+(height-120),width-20,60);
}
public void setName(String s)
{
name=s;
}
public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)
{
this.socket=socket;
this.in=in;
this.out=out;
try
{
threadMessage.start();
}
catch(Exception e)
{
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==確定||e.getSource()==送出信息)
{
String message="";
String people=privateChatList.getSelectedItem();
people=people.substring(0,people.indexOf("("));
message=送出信息.getText();
if(message.length()>0)
{
try {
if(people.equals("大家"))
{
out.writeUTF("公共聊天內容:"+name+"說:"+message);
}
else
{
out.writeUTF("私人聊天內容:"+name+"悄悄地說:"+message+"#"+people);
}
}
catch(IOException event)
{
}
}
}
else if(e.getSource()==listComponent)
{
privateChatList.insert(listComponent.getSelectedItem(),0);
privateChatList.repaint();
}
else if(e.getSource()==刷新談話區)
{
談話顯示區.setText(null);
}
else if(e.getSource()==刷新私聊區)
{
私聊顯示區.setText(null);
}
}
public void run()
{
while(true)
{
String s=null;
try
{
s=in.readUTF();
if(s.startsWith("聊天內容:"))
{
String content=s.substring(s.indexOf(":")+1);
談話顯示區.append("\n"+content);
}
if(s.startsWith("私人聊天內容:"))
{
String content=s.substring(s.indexOf(":")+1);
私聊顯示區.append("\n"+content);
}
else if(s.startsWith("聊天者:"))
{
String people=s.substring(s.indexOf(":")+1,s.indexOf("性別"));
String sex=s.substring(s.indexOf("性別")+2);
listTable.put(people,people+"("+sex+")");
listComponent.add((String)listTable.get(people));
listComponent.repaint();
}
else if(s.startsWith("用戶離線:"))
{
String awayPeopleName=s.substring(s.indexOf(":")+1);
listComponent.remove((String)listTable.get(awayPeopleName));
listComponent.repaint();
談話顯示區.append("\n"+(String)listTable.get(awayPeopleName)+"離線");
listTable.remove(awayPeopleName);
}
Thread.sleep(5);
}
catch(IOException e)
{
listComponent.removeAll();
listComponent.repaint();
listTable.clear();
談話顯示區.setText("和伺服器的連接已中斷\n必須刷新瀏覽器才能再次聊天");
break;
}
catch(InterruptedException e)
{
}
}
}
}
ChatServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer
{
public static void main(String args[])
{
ServerSocket server=null;
Socket you=null;
Hashtable peopleList;
peopleList=new Hashtable();
while(true)
{
try
{
server=new ServerSocket(6666);
}
catch(IOException e1)
{
System.out.println("正在監聽");
}
try {
you=server.accept();
InetAddress address=you.getInetAddress();
System.out.println("用戶的IP:"+address);
}
catch (IOException e)
{
}
if(you!=null)
{
Server_thread peopleThread=new Server_thread(you,peopleList);
peopleThread.start();
}
else {
continue;
}
}
}
}
class Server_thread extends Thread
{
String name=null,sex=null;
Socket socket=null;
File file=null;
DataOutputStream out=null;
DataInputStream in=null;
Hashtable peopleList=null;
Server_thread(Socket t,Hashtable list)
{
peopleList=list;
socket=t;
try {
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException e)
{
}
}
public void run()
{
while(true)
{ String s=null;
try
{
s=in.readUTF();
if(s.startsWith("姓名:"))
{
name=s.substring(s.indexOf(":")+1,s.indexOf("性別"));
sex=s.substring(s.lastIndexOf(":")+1);
boolean boo=peopleList.containsKey(name);
if(boo==false)
{
peopleList.put(name,this);
out.writeUTF("可以聊天:");
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{
Server_thread th=(Server_thread)enum.nextElement();
th.out.writeUTF("聊天者:"+name+"性別"+sex);
if(th!=this)
{
out.writeUTF("聊天者:"+th.name+"性別"+th.sex);
}
}
}
else
{
out.writeUTF("不可以聊天:");
}
}
else if(s.startsWith("公共聊天內容:"))
{
String message=s.substring(s.indexOf(":")+1);
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{
((Server_thread)enum.nextElement()).out.writeUTF("聊天內容:"+message);
}
}
else if(s.startsWith("用戶離開:"))
{
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{ try
{
Server_thread th=(Server_thread)enum.nextElement();
if(th!=this&&th.isAlive())
{
th.out.writeUTF("用戶離線:"+name);
}
}
catch(IOException eee)
{
}
}
peopleList.remove(name);
socket.close();
System.out.println(name+"用戶離開了");
break;
}
else if(s.startsWith("私人聊天內容:"))
{
String 悄悄話=s.substring(s.indexOf(":")+1,s.indexOf("#"));
String toPeople=s.substring(s.indexOf("#")+1);
Server_thread toThread=(Server_thread)peopleList.get(toPeople);
if(toThread!=null)
{
toThread.out.writeUTF("私人聊天內容:"+悄悄話);
}
else
{
out.writeUTF("私人聊天內容:"+toPeople+"已經離線");
}
}
}
catch(IOException ee)
{
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{ try
{
Server_thread th=(Server_thread)enum.nextElement();
if(th!=this&&th.isAlive())
{
th.out.writeUTF("用戶離線:"+name);
}
}
catch(IOException eee)
{
}
}
peopleList.remove(name);
try
{
socket.close();
}
catch(IOException eee)
{
}
System.out.println(name+"用戶離開了");
break;
}
}
}
}
import java.awt.*;
import java.io.*;
import java.net.*;
import java.applet.*;
import java.util.Hashtable;
ClientChat.java
public class ClientChat extends Applet implements Runnable
{
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
InputNameTextField 用戶提交昵稱界面=null;
ChatArea 用戶聊天界面=null;
Hashtable listTable;
Label 提示條;
Panel north, center;
Thread thread;
public void init()
{
int width=getSize().width;
int height=getSize().height;
listTable=new Hashtable();
setLayout(new BorderLayout());
用戶提交昵稱界面=new InputNameTextField(listTable);
int h=用戶提交昵稱界面.getSize().height;
用戶聊天界面=new ChatArea("",listTable,width,height-(h+5));
用戶聊天界面.setVisible(false);
提示條=new Label("正在連接到伺服器,請稍等...",Label.CENTER);
提示條.setForeground(Color.red);
north=new Panel(new FlowLayout(FlowLayout.LEFT));
center=new Panel();
north.add(用戶提交昵稱界面);
north.add(提示條);
center.add(用戶聊天界面);
add(north,BorderLayout.NORTH);
add(center,BorderLayout.CENTER);
validate();
}
public void start()
{
if(socket!=null&&in!=null&&out!=null)
{ try
{
socket.close();
in.close();
out.close();
用戶聊天界面.setVisible(false);
}
catch(Exception ee)
{
}
}
try
{
socket = new Socket(this.getCodeBase().getHost(), 6666);
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException ee)
{
提示條.setText("連接失敗");
}
if(socket!=null)
{
InetAddress address=socket.getInetAddress();
提示條.setText("連接:"+address+"成功");
用戶提交昵稱界面.setSocketConnection(socket,in,out);
north.validate();
}
if(thread==null)
{
thread=new Thread(this);
thread.start();
}
}
public void stop()
{
try
{
socket.close();
thread=null;
}
catch(IOException e)
{
this.showStatus(e.toString());
}
}
public void run()
{
while(thread!=null)
{
if(用戶提交昵稱界面.get能否聊天()==true)
{
用戶聊天界面.setVisible(true);
用戶聊天界面.setName(用戶提交昵稱界面.getName());
用戶聊天界面.setSocketConnection(socket,in,out);
提示條.setText("祝聊天愉快!");
center.validate();
break;
}
try
{
Thread.sleep(100);
}
catch(Exception e)
{
}
}
}
}
InputNameTextField。java
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.io.*;
import java.util.Hashtable;
public class InputNameTextField extends Panel implements ActionListener,Runnable
{
TextField nameFile=null;
String name=null;
Checkbox male=null,female=null;
CheckboxGroup group=null;
Button 進入聊天室=null,退出聊天室=null;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread=null;
boolean 能否聊天=false;
Hashtable listTable;
public InputNameTextField(Hashtable listTable)
{
this.listTable=listTable;
nameFile=new TextField(10);
group=new CheckboxGroup();
male=new Checkbox("男",true,group);
female=new Checkbox("女",false,group);
進入聊天室=new Button("進入");
退出聊天室=new Button("退出");
進入聊天室.addActionListener(this);
退出聊天室.addActionListener(this);
thread=new Thread(this);
add(new Label("昵稱:"));
add(nameFile);
add(male);
add(female);
add(進入聊天室);
add(退出聊天室);
退出聊天室.setEnabled(false);
}
public void set能否聊天(boolean b)
{
能否聊天=b;
}
public boolean get能否聊天()
{
return 能否聊天;
}
public String getName()
{
return name;
}
public void setName(String s)
{
name=s;
}
public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)
{
this.socket=socket;
this.in=in;
this.out=out;
try{
thread.start();
}
catch(Exception e)
{
nameFile.setText(""+e);
}
}
public Socket getSocket()
{
return socket;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==進入聊天室)
{
退出聊天室.setEnabled(true);
if(能否聊天==true)
{
nameFile.setText("您正在聊天:"+name);
}
else
{
this.setName(nameFile.getText());
String sex=group.getSelectedCheckbox().getLabel();
if(socket!=null&&name!=null)
{
try{
out.writeUTF("姓名:"+name+"性別:"+sex);
}
catch(IOException ee)
{
nameFile.setText("沒有連通伺服器"+ee);
}
}
}
}
if(e.getSource()==退出聊天室)
{
try
{
out.writeUTF("用戶離開:");
}
catch(IOException ee)
{
}
}
}
public void run()
{
String message=null;
while(true)
{
if(in!=null)
{
try
{
message=in.readUTF();
}
catch(IOException e)
{
nameFile.setText("和伺服器斷開"+e);
}
}
if(message.startsWith("可以聊天:"))
{
能否聊天=true;
break;
}
else if(message.startsWith("聊天者:"))
{
String people=message.substring(message.indexOf(":")+1);
listTable.put(people,people);
}
else if(message.startsWith("不可以聊天:"))
{
能否聊天=false;
nameFile.setText("該昵稱已被佔用");
}
}
}
}
⑷ 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();
}
}
⑸ 求助高人:編輯簡單聊天工具
我這里有一個簡單的聊天室程序:包括伺服器和客戶端
用VB的winsock實現的,需要跟我聯系就是,免費贈送。
QQ361656515
網路編程——聊天室(代碼如下)
本程序是基於VB開發環境中Winsock控制項的應用,遵循TCP/IP協議,利用該控制項的套接字功能,實現遠程計算機之間數據通信的,它由伺服器和客戶端組成。伺服器用於連接多個客戶端,可以統計已經連接過伺服器的人數和伺服器當前的在線人數,並負責收發各客戶發送的消息,實現多個客戶之間實時、准確、無誤的數據通信。該程序可以連接1000個客戶端,而如果要增減可供連接的客戶端,只需對源程序的客戶上限稍加改動即可。
工作原理
伺服器:運行時聲明一組Winsock控制項數組,只創建該數組的第一個數組元素並從9999埠開始偵聽(listen),當有客戶端連接第一個Winsock控制項並且連接成功時,觸發Winsock_ConnectRequest()事件,埠數(Localport)遞減1單位,此時運用Load Winsock(i)方法創建下一個Winsock控制項數組元素並讓它開始偵聽,繼續等待新客戶端的連接,如此往復。當連接人數達到既定的客戶端上限時,伺服器便停止創建新的Winsock控制項數組元素,停止偵聽,即停止連接客戶。伺服器與客戶端連接成功之後,通過Winsock的DataArrival()事件、SendData和GetData方法來實現數據的發送和接收。伺服器中用一個Locked屬性設定為True的文本框來記錄所有客戶發送的消息(聊天記錄)。
客戶端:運行時只創建一個Winsock控制項,從9999開始遞減依次指定Winsock的遠程埠並依次連接遠程伺服器,一旦連接成功就停止指定埠,且由此可以開始和伺服器通信。
用一個Locked屬性設定為True的文本框來記錄所有客戶發送的消息,用一個可編輯的文本框來輸入客戶要發送的消息,這樣就基本實現了聊天室的功能。
程序代碼
伺服器:
Option Explicit
Dim guest As Integer '在線客戶數量計數器
Dim j As Integer '已接客戶數量計數器
Dim k As Integer '向在線客戶發送消息數量計數器
Dim t As Integer '關閉伺服器時向在線客戶發送消息數量計數器
Dim port As Integer '埠計數器
Dim msg As String '收發的消息文本
Dim newguest As Integer '新客戶連接
Private Sub Form_Load()
If App.PrevInstance Then MsgBox "對不起!您已經創建了一個伺服器^_^": End
j = 0
guest = 0
port = 9999
Text2 = Winsock1(0).LocalIP
Label3.Caption = "在線人數:" & guest
Label4.Caption = "已接人數:" & j
Winsock1(0).LocalPort = port 'Winsock控制項數組第一個控制項開始偵聽
Winsock1(0).Listen
End Sub
Private Sub Form_Unload(Cancel As Integer) '關閉伺服器時緩沖,發送斷開信號
Cancel = 1
t = 0
Timer2.Enabled = 1
End Sub
Private Sub Timer1_Timer()
On Error Resume Next '錯誤處理
Winsock1(k).SendData msg '向所有客戶發送即時收到的消息
k = k + 1
If k >= j Then Timer1.Enabled = 0
End Sub
Private Sub Timer2_Timer() '向客戶發送斷開信號
On Error Resume Next
msg = "closewinsock"
Winsock1(t).SendData msg
t = t + 1
If t > j Then End
End Sub
Private Sub Timer3_Timer() '向新客戶發送歡迎信息
On Error Resume Next
If k = newguest Then Exit Sub
Winsock1(k).SendData msg
k = k + 1
If k >= j Then Timer3.Enabled = 0
End Sub
Private Sub Winsock1_ConnectionRequest(Index As Integer, ByVal requestID As Long)
On Error Resume Next
Dim onlineperson As String
msg = ""
If Winsock1(Index).State <> sckClosed Then Winsock1(Index).Close '成功連接
Winsock1(Index).Accept requestID
j = j + 1 '統計已接人數
If guest + 1 < 10 Then
onlineperson = "currentonlineperson00" + CStr(guest + 1) + msg
ElseIf guest + 1 < 100 Then
onlineperson = "currentonlineperson0" + CStr(guest + 1) + msg
End If
Winsock1(Index).SendData onlineperson & "您是第" & CStr(j) & "位進入本聊天室的客戶^_^" + Chr(13) + Chr(10)
msg = onlineperson & "第" & CStr(j) & "位客戶進入了本聊天室" + Chr(13) + Chr(10)
Text1 = Text1 +"第" & CStr(j) & "位客戶進入了本聊天室" + Chr(13) + Chr(10)
k = 0
newguest = Index
Timer3.Enabled = 1
Text1.SelStart = Len(Text1)
guest = guest + 1 '統計在線人數
Label3.Caption = "在線人數:" & guest
Label4.Caption = "已接人數:" & j
Load Winsock1(j)
port = port - 1
Winsock1(j).LocalPort = port
Winsock1(j).Listen
End Sub
Private Sub Winsock1_DataArrival(Index As Integer, ByVal bytesTotal As Long)
On Error Resume Next
Dim i As Integer
Dim onlineperson As String
msg = ""
Winsock1(Index).GetData msg '發送斷開信號
If msg = "closewinsock" Then
msg = ""
Winsock1(Index).Close
If guest - 1 < 10 Then
onlineperson = "currentonlineperson00" + CStr(guest - 1)
ElseIf guest < 100 Then
onlineperson = "currentonlineperson0" + CStr(guest - 1)
End If
msg = "第" & CStr(Index + 1) & "位客戶已經離開" + Chr(13) + Chr(10)
Text1 = Text1 + msg
msg = onlineperson & "第" & CStr(Index + 1) & "位客戶已經離開" + Chr(13) + Chr(10)
Text1.SelStart = Len(Text1)
k = 0
Timer1.Enabled = 1
guest = guest - 1
Label3.Caption = "在線人數:" & guest
Label4.Caption = "已接人數:" & j
Exit Sub
End If
msg = "第" + CStr(Index + 1) + "位客戶說:" + msg + Chr(13) + Chr(10)
Text1 = Text1 + msg
Text1.SelStart = Len(Text1)
k = 0
Timer1.Enabled = 1
End Sub
客戶端:
Dim linkstate As Boolean '判斷連接狀態
Dim port As Integer '依次嘗試連接的埠
Private Sub Cmdconnect_Click()
On Error Resume Next
Dim t As String
Dim x As String
Dim y As Integer
y = 0
If Len(Text1) = 0 Then Exit Sub '判斷輸入的IP地址是否合法
For i = 1 To Len(Text1)
If Mid(Text1, i, 1) <> "." Then
t = t + Mid(Text1, i, 1)
x = ""
Else
y = y + 1
x = x + Mid(Text1, i, 1)
t = ""
End If
If Len(t) > 3 Or x = ".." Or Left(Text1, 1) = "." Or Right(Text1, 1) = "." Then
MsgBox "請輸入正確的IP地址^_^", vbOKOnly + vbInformation, "連接": Exit Sub
End If
Next i
If y <> 3 Then MsgBox "請輸入正確的IP地址^_^", vbOKOnly + vbInformation, "連接": Exit Sub
If Text1 Like "*.*.*.*" Then
If Cmdconnect.Caption = "&Link" Then '用戶選擇連接
Cmdconnect.Caption = "&Break"
Timer1.Enabled = 1
Text1.Enabled = 0
Else '用戶選擇中斷連接
Label4.Caption = "在線人數:0"
Text2 = Text2 + "連接中斷" + Chr(13) + Chr(10)
Text2.SelStart = Len(Text2)
Timer1.Enabled = 0
Text1.Enabled = 1
Text1.SetFocus
Cmdconnect.Caption = "&Link"
Winsock1.SendData "closewinsock"
linkstate = False
port = 9999
Text3.Enabled = False
cmdsend.Enabled = False
End If
End If
End Sub
Private Sub cmdsend_Click()
On Error Resume Next '發送消息
Winsock1.SendData Text3
Text3 = ""
Text3.SetFocus
End Sub
Private Sub Form_Load()
linkstate = False
port = 9999
End Sub
Private Sub Form_Unload(Cancel As Integer)
On Error Resume Next
Winsock1.SendData "closewinsock" '向伺服器發送斷開信號
Cancel = 1
Timer2.Enabled = 1
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer) '禁止用戶輸入非法IP地址
If KeyAscii < 48 Or KeyAscii > 57 Then
If KeyAscii <> 8 And KeyAscii <> 46 Then KeyAscii = 0
End If
End Sub
Private Sub Text2_KeyPress(KeyAscii As Integer)
If Text3.Enabled = False Then Exit Sub
If KeyAscii = 13 Then Call cmdsend_Click
Text3 = Text3 + Chr(KeyAscii)
End Sub
Private Sub Text3_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then Call cmdsend_Click
End Sub
Private Sub Timer1_Timer() '從9999埠依次嘗試連接伺服器
If linkstate = True Then Exit Sub
Winsock1.Close
Winsock1.RemoteHost = Text1.Text
Winsock1.RemotePort = port
Winsock1.Connect
port = port - 1
If port < 9000 Then '設置可供連接的埠上限
Timer1.Enabled = 0
Text1.Enabled = 1
Cmdconnect.Caption = "&Link"
port = 9999
MsgBox "無法連接到伺服器,請檢查網路連接狀況", vbOKOnly + vbCritical, "連接"
End If
End Sub
Private Sub Timer2_Timer() '緩沖以發送斷開信號
End
End Sub
Private Sub Winsock1_Connect()
port = port + 1
Timer1.Enabled = 0
linkstate = True
Text3.Enabled = 0
cmdsend.Enabled = 0
MsgBox "已經成功連接", vbOKOnly + vbInformation, "連接"
Text3.Enabled = 1
cmdsend.Enabled = 1
Text3.SetFocus
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim msg As String
Winsock1.GetData msg '接收伺服器傳來的的數據並進行相應處理
If Left(CStr(msg), 19) = "currentonlineperson" Then
Label4.Caption = "在線人數:" & Str(Val(Mid(CStr(msg), 20, 3)))
msg = Right(CStr(msg), Len(CStr(msg)) - 22)
End If
If CStr(msg) = "closewinsock" Then
Call Cmdconnect_Click
Text2.SelStart = Len(Text2)
Exit Sub
End If
Text2 = Text2 + msg
Text2.SelStart = Len(Text2)
End Sub
⑹ java寫一個簡單的支持多人聊天的聊天室代碼,不要用UI圖形界面
我發現一個大蝦的BLOG里有:
你自己去看一下,對不對你的胃口哦,我對JAVA不了解?