導航:首頁 > 編程語言 > javasocket仿qq

javasocket仿qq

發布時間:2024-06-24 13:07:02

㈠ 怎樣有java socket實現發送接受表情類似qq詳細點代碼

哈 我正好在做一個類似qq的系統,不過還沒完工,不過可以運行,現在只實現了登錄,顯示分組,列出好友,查看好友信息功冊,看看代碼吧
哎 類太多了,像什麼vo類及實現類我就不發了,再說這些類沒什麼技術含量
如果有必要的話 你留下郵箱,我將兩個工程和資料庫代碼發給你
伺服器類:
package chat;

import impl.UserImpl;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import vo.Userinfo;
import .UserDao;

/**
* 伺服器類,用於接受來自客戶端的請求,本系統規定來自客戶端每一次請求 所傳過來的參數不少於兩個,第一個用來標識此次請求將做什麼操作,後面
* 的參數為客戶端請求服務所需的必要參數
*
* @author 程勝
* @version 0.1
* @date 09-01-08
*
*/
public class ChatServer extends Thread {
// 定義最大連接數
private static final int MAXLINK = 50;

// 記錄當前連接數
public static int linkNum = 0;

// 定義服務連接對象
private static ServerSocket ss;

public static void main(String[] args) throws Exception {
// 實例化服務類
ss = new ServerSocket(8001);
// 啟用多線程:其實就是調用run方法,好像沒必要另啟線程,哎 寫好了 就不改了
new ChatServer().start();
System.out.println("伺服器已成功啟動…………");
}

/*
* 覆寫run方法
*/
public void run() {
Socket soc = null;
try {
// 循環監聽客戶端請求
while (true) {
while (true) {
// 如果連接數已滿,則等待
if (linkNum >= MAXLINK)
this.sleep(100);
else {
break;
}
}
// 監聽請求
soc = ss.accept();
// 將連接加一
linkNum++;
// 獲得socket對象後調用處理類
new Operate(soc);
}
} catch (Exception e) {
System.out.println(e);
} finally {
if (soc != null) {
try {
soc.close();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("伺服器出現莫名故障,伺服器退出!");
}
}

}
}

/**
* 操作類,用來處理來自客戶端的請求
*
* @author Administrator
*
*/
class Operate {
// 接定義用於實別客戶端發來的頭號請求將做何操作的變數
private String operate;

/**
* 以下幾行用於聲明網路操作的必要變數
*/
private Socket soc = null;

private InputStream ips = null;

private OutputStream ops = null;

private ObjectOutputStream soops = null;

private ObjectInputStream soips = null;

/**
* 構造函數,在其中為以上定義的變數的賦值
*
* @param soc
*/
Operate(Socket soc) {
this.soc = soc;
try {
ips = soc.getInputStream();
ops = soc.getOutputStream();
soips = new ObjectInputStream(ips);
// 接收從客戶端發來的頭號請求,它用於實別此次請求的內容
operate = soips.readObject().toString();
} catch (Exception e) {
System.out.println(e);
}
// 調用實際操作方法
whichOpe();

}

/**
* 判斷是哪個操作
*/
private void whichOpe() {
if ("login".equals(operate)) {
login();
} else {
if ("".equals(operate)) {

}
}
}

/**
* 連接資料庫,進行登錄驗證
*/
private void login() {
UserDao user = new UserImpl();
Userinfo user = null;
try {
// 讀取從客戶端傳過來的數據
user = (Userinfo) soips.readObject();
user = user.login(user);
soops = new ObjectOutputStream(ops);
// 將結果傳給客戶端
soops.writeObject(user);
soops.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
soops.close();
soips.close();
soc.close();
// 將連接數減一
ChatServer.linkNum--;

} catch (IOException e) {
System.out.println(e);
}
}
}
}
客戶端的兩個類:
package client;

import java.awt.Font;
import java.awt.GridLayout;
import java.awt.TextField;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import vo.Userinfo;

/**
* 登錄界面,繼承自jframe類
*
* @author 程勝
* @version 0.1
* @date 09-01-08
* @address 學校寢室:綜合樓424
*
*/
public class Login extends JFrame {
private final int TEXTSIZE = 10;// 定義文本長度的值

private JLabel lname = new JLabel("用戶名");

private JLabel lpassword = new JLabel("密碼");

private JLabel lhead = new JLabel("用戶登錄");

private JButton bok = new JButton("登錄");

private JButton bcancel = new JButton("退出");

private JPanel pcenter = new JPanel();

private JPanel pname = new JPanel();

private JPanel ppwd = new JPanel();

private JPanel psouth = new JPanel();

private JPanel pnorth = new JPanel();

private TextField pwd = new TextField(TEXTSIZE);

private JTextField name = new JTextField(TEXTSIZE);

private GridLayout glayout = new GridLayout();

public Login() {
// 設置界面大小及位置
this.setBounds(300, 200, 320, 250);
this.setTitle("用戶登錄");
this.setResizable(false);
// 設置窗口的關閉方式
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
// 布置窗口
this.frameLayout();
// 添加事件
this.addAction();
// 顯示窗口
this.show();
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Login();
}

/**
* 布置容器
*/
private final void frameLayout() {
lhead.setFont(new Font("", Font.BOLD, 28));
glayout.setColumns(1);
glayout.setRows(2);
pcenter.setLayout(glayout);
pname.add(lname);
pname.add(name);
pwd.setEchoChar('*');
ppwd.add(lpassword);
ppwd.add(pwd);
pnorth.add(lhead);
psouth.add(bok);
psouth.add(bcancel);
pcenter.add(pname);
pcenter.add(ppwd);
this.add(pnorth, "North");
this.add(pcenter, "Center");
this.add(psouth, "South");
}

/**
* 添加事件
*/
private final void addAction() {
bok.addActionListener(new AddAction());
bcancel.addActionListener(new AddAction());
name.addActionListener(new AddAction());
pwd.addActionListener(new AddAction());

}

/**
* 此類為內置類,用於事件處理
*
* @author Administrator
*
*/
private class AddAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == bcancel) {
System.exit(0);

} else {
if ("".equals(name.getText()) || "".equals(pwd.getText())) {
JOptionPane.showMessageDialog(Login.this, "用戶名和密碼不能為空");
} else {
try {
// 判斷輸入的數據是否合法
Integer.parseInt(name.getText());
} catch (Exception ex) {
JOptionPane.showMessageDialog(Login.this, "請正確輸入號碼");
return;
}
new TcpLogin(name.getText(), pwd.getText()).check();
}
}
}

}

/**
* 登錄驗證類,內置類 將用戶名和密碼傳到伺服器做驗證
*
* @author 程勝
* @version 0.1
* @date 09-01-08
*/
class TcpLogin {
private int name;

private String pwd = "";

/**
* 構造函數,初始化用戶名和密碼的值
*
* @param name
* @param pwd
*/
TcpLogin(String name, String pwd) {
this.name = Integer.parseInt(name);
this.pwd = pwd;
}

/**
* 連接伺服器,驗證用戶信息方法
*/
void check() {
Window waitWin=new Window(Login.this);
// 獲得界面
Login login = Login.this;
Userinfo user = new Userinfo();
user.setUserId(name);
user.setPassword(pwd);
Socket soc = null;
InputStream ips = null;
OutputStream ops = null;
ObjectInputStream coips = null;
ObjectOutputStream coops = null;
try {
soc = new Socket("127.0.0.1", 8001);
ips = soc.getInputStream();
ops = soc.getOutputStream();

coops = new ObjectOutputStream(ops);
coops.writeObject("login");
coops.writeObject(user);
coops.flush();

ObjectInputStream oips = new ObjectInputStream(ips);
user = null;
user = (Userinfo) oips.readObject();
if (user != null){
new XiHa(user);
login.dispose();
}
else {
JOptionPane.showMessageDialog(login, "用戶名和密碼錯誤");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ips.close();
ops.close();
soc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

}
package client;

import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.jscrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.Timer;
import javax.swing.tree.DefaultMutableTreeNode;

import vo.Groupinfo;
import vo.Relationinfo;
import vo.Userinfo;

/**
* 此類為本程序客戶端的主界面,剛想了好會兒決定取名叫』嘻哈『 意為』嘻嘻哈哈『
*
* @author 程勝
* @version 0.1
* @date 09-01-08
* @address 學校寢室:綜合樓424
*/
public class XiHa extends JFrame {
// 好友信息
static List<Userinfo> friends = new ArrayList<Userinfo>();
// 用戶信息
private Userinfo user = null;

private JPanel ptree = new JPanel();

private JPanel psouth = new JPanel();

private JButton bfind = new JButton("查找");

private JButton bsystem = new JButton("系統設置");

/**
* 構造函數,設置界面基本參數
*/
public XiHa(Userinfo user) {
this.user = user;
this.setTitle("嘻嘻哈哈");
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setBounds(800, 100, 200, 500);
this.setResizable(false);
// 布置界面
initFrame();
// this.pack();
this.setVisible(true);
}

/**
* 用於界面布置
*/
private void initFrame() {
ptree.add(new JScrollPane(new CreateTree(user).createNode()));
psouth.add(bsystem);
psouth.add(bfind);
this.add(ptree, "Center");
this.add(psouth, "South");

}
}

/**
* 本類用於創建以用戶信息為節點的樹
*
* @author 程勝
* @version 0.1
* @date 09-01-08
* @address 學校寢室:綜合樓424
*
*/
class CreateTree {
JTree tree=null;
private Userinfo user = null;

CreateTree(Userinfo user) {
this.user = user;
}

/**
* 用伺服器傳回的數據創建一棵樹
*
* @return
*/
JTree createNode() {
//根結點
DefaultMutableTreeNode all = new DefaultMutableTreeNode("所有好友");
Set<Groupinfo> groups = user.getGroupinfos();
Set<Relationinfo> relations = user.getRelationinfosForUserId();
Iterator<Groupinfo> ig = groups.iterator();
Iterator<Relationinfo> ir = null;
Groupinfo group = null;
Relationinfo relation = null;
DefaultMutableTreeNode friendNode = null;
Userinfo friend = null;
while (ig.hasNext()) {
group = ig.next();
friendNode = new DefaultMutableTreeNode(group.getGroupName());

ir = relations.iterator();
while (ir.hasNext()) {
relation = ir.next();
if (relation.getResideGroupId() == group.getGroupId()) {
friend = relation.getFriend();
friendNode.add(new DefaultMutableTreeNode(friend
.getPetname()
+ "(" + relation.getFriendId() + ")"));
XiHa.friends.add(friend);
}
}
all.add(friendNode);
// rootTree.add(friendNode);
}
tree=new JTree(all);
tree.addMouseListener(new TreeListener());
return tree;
}
/**
* 此類為創建樹的內置類,用於對結點的事件處理
*
* @author 程勝
* @version 0.1
* @date 09-01-09
* @address 學校寢室:綜合樓424
*/
class TreeListener extends MouseAdapter{
private JFrame friendInfo=null;
private String nodeInfo="";
//用於區分單擊雙擊
Timer mouseTimer =null;
/*
* 覆寫mouseAdapter中的mouseClicked方法,滑鼠點擊時觸發
*/
public void mouseClicked(MouseEvent e){

//返回選定的結點
DefaultMutableTreeNode treeNode =null;
treeNode =(DefaultMutableTreeNode)CreateTree.this.tree.getLastSelectedPathComponent();
if(treeNode==null)return;
//如果它不是葉子結點就返回
if(!treeNode.isLeaf())return;

nodeInfo=treeNode.toString();
if(e.getClickCount()==1){
mouseTimer = new javax.swing.Timer(350, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//布置信息界面
initFriendInfo();
mouseTimer.stop();
}
});
mouseTimer.restart();

}else{
if(e.getClickCount()==2&&mouseTimer.isRunning()){
mouseTimer.stop();
//實例化聊天界面
new WinChat();
}

}

}

/**
* 布置friendInfo的界面
*/
private void initFriendInfo() {
friendInfo=new JFrame();
friendInfo.setSize(300,120);
friendInfo.setDefaultCloseOperation(friendInfo.DISPOSE_ON_CLOSE);
friendInfo.setLocationRelativeTo(null);
friendInfoContent(this.treat());
friendInfo.setVisible(true);

}
/**
* 設置窗口中的具體內容
* @param friendId
* @return
*/
private void friendInfoContent(int friendId) {
friendInfo.dispose();
Userinfo friend=this.findFriend(friendId);
JPanel pmain=new JPanel();
pmain.setLayout(new GridLayout(3,1));
JPanel panel1=new JPanel();
panel1.add(new JLabel("嘻哈號:"+friend.getUserId()+" "+"昵稱:"+friend.getPetname()));
JPanel panel2=new JPanel();
panel2.add(new JLabel("姓名:"+(friend.getName()==null?"":friend.getName())+" "+"年齡:"+friend.getAge()+" "+"性別:"+friend.getSex()));
JPanel panel3=new JPanel();
panel3.add(new JLabel("個性簽名: "+(friend.getAutograph()==null?"":friend.getAutograph())));
pmain.add(panel1);pmain.add(panel2);pmain.add(panel3);
friendInfo.add(pmain);
}
/**
* 此方法用於獲得好友的id號 從節點上的文本中獲取
* @return 好友id
*/
private int treat(){
int len=nodeInfo.getBytes().length;
int friendId=Integer.parseInt(new String(nodeInfo.getBytes(),len-5,4));
return friendId;

}
/**
* 此方法用於按id查找好友信息
* @param friendId
* @return 好友信息
*/
private Userinfo findFriend(int friendId){
Userinfo friend=null;
Iterator friends=XiHa.friends.iterator();
while(friends.hasNext()){
Userinfo ifriend=(Userinfo)friends.next();
if(ifriend.getUserId()==friendId){
friend=ifriend;
break;
}
}
return friend;

}

}
}
/**
* 本類聊天窗口類,還不知道該怎麼寫,現在有點茫然,剛跟網友交流了一下
* 覺得前面寫的通信代碼很不規范,應該重新寫,哎 先把界面寫好再說
*
* 一會兒就要回去過年了,可能就沒那麼時間寫這個系統了
* @author 程勝
* @version 0.1
* @date 09-01-11
* @address 學校寢室:綜合樓424
*
*/
class WinChat extends JFrame{
private JPanel pmain=new JPanel();
private JPanel pcether=new JPanel();
private JPanel psouth=new JPanel();
//private JTextArea precod=new JTextArea(JTextArea.);
}

㈡ 用JAVA怎麼寫QQ

用java是可以寫出qq的,只不過用java開發c/s的軟體不是java特長的,你要是真的想寫,就寫著練練手吧,最起碼可以鞏固java se上的知識。
具體怎麼寫,給你個大概的思路吧,因為我沒辦法在這個有限的輸入框內把所有的代碼寫完。
【1】先寫出qq的簡單界面
【2】給每個按鈕添加監聽
【3】按鈕事件(方法)定義
【4】連接網路(socket)
【5】測試
【5】其他功能添加
【6】測試

㈢ 用Java編寫類似QQ對話框程序

給你個Socket/ServerSocket寫的小例子,看看能不能幫到你哦:
先運行ServerGUI,啟動伺服器端,再運行ClientGUI,雙方就可以發送字元串了...

ServerGUI類:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

@SuppressWarnings("serial")
public class ServerGUI extends JFrame {
private JTextArea jta, jtaInput;

private JPanel jtaAreaPane;

private JPanel j;

private JButton buttonSubmit, buttonExit;

private String stringGet = null;

private OurServer os = null;

public ServerGUI(String s) {
super(s);

jtaAreaPane = new JPanel();
jtaAreaPane.setLayout(new GridLayout(2, 1));

jta = new JTextArea(7, 35);
jta.setLineWrap(true);
jta.setBackground(new Color(169, 255, 128));
JScrollPane jsp = new JScrollPane(jta);

jtaInput = new JTextArea(7, 35);
jtaInput.setLineWrap(true);
jtaInput.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
String s = jtaInput.getText();
jtaInput.setText(null); // 輸入框重新設為空
jta.append("\n" + "你發送了:" + s.trim());
stringGet = s;

if (stringGet != null) {
System.out.println("stringGet:" + stringGet);
try {
os.getOsw().write(stringGet + "\n");
os.getOsw().flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
});
jtaInput.setBackground(new Color(133, 168, 250));
JScrollPane jspIn = new JScrollPane(jtaInput);

jtaAreaPane.add(jsp);
jtaAreaPane.add(jspIn);

j = new JPanel();

buttonSubmit = new JButton("提交");
buttonSubmit.addActionListener(new SetButtonSubmit());
buttonExit = new JButton("關閉");
buttonExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
j.add(buttonSubmit);
j.add(buttonExit);

setLayout(new BorderLayout());
add(jtaAreaPane, BorderLayout.CENTER);
add(j, BorderLayout.SOUTH);

setSize(new Dimension(400, 500));
setLocation(500, 300);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);

new Thread(new ServerOurRead()).start();

os = new OurServer();

}

public String GetString() {
return stringGet;
}

public void setStringGet(String s) {
this.stringGet = s;
}

class SetButtonSubmit implements ActionListener {
@SuppressWarnings("static-access")
public void actionPerformed(ActionEvent e) {
String s = jtaInput.getText();
jtaInput.setText(null);
jta.append("\n" + "你發送了:" + s.trim());// jta.setText("你發送了:"+oc.s);
stringGet = s;

if (stringGet != null) {
System.out.println("stringGet:" + stringGet);
try {
os.getOsw().write(stringGet + "\n");
os.getOsw().flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}

// 接收來自客戶端的線程
class ServerOurRead implements Runnable {
public void run() {
while (true) {
try {
jta.append("\n來自客戶端:" + os.getBr().readLine());
} catch (Exception e1) {
e1.printStackTrace();
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public static void main(String args[]) {
new ServerGUI("伺服器對話框");
}
}

OurServer類:

import java.util.*;
import java.io.*;
import java.net.*;

public class OurServer {

private ServerSocket serverSocket = null;

private OutputStream os = null;

private InputStream is = null;

private OutputStreamWriter osw = null;

private InputStreamReader isr = null;

private BufferedReader br = null;

private ArrayList<Socket> socketList = null;

private Scanner console = new Scanner(System.in);

public OurServer() {

try {
serverSocket = new ServerSocket(22222);

System.out.println("serverSocket is waiting...");

Socket soc = serverSocket.accept();

os = soc.getOutputStream();
is = soc.getInputStream();

osw = new OutputStreamWriter(os);
isr = new InputStreamReader(is);

br = new BufferedReader(isr);

} catch (IOException e) {
e.printStackTrace();
}
}

// 從客戶端讀信息的線程

public static void main(String args[]) {
}

public BufferedReader getBr() {
return br;
}

public void setBr(BufferedReader br) {
this.br = br;
}

public OutputStreamWriter getOsw() {
return osw;
}

public void setOsw(OutputStreamWriter osw) {
this.osw = osw;
}
}

ClientGUI類:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

@SuppressWarnings("serial")
public class ClientGUI extends JFrame {
private JTextArea jta, jtaInput;

private JPanel jtaAreaPanel;

private JPanel j;

private JButton buttonSubmit, buttonExit;

private String stringGet = null;

private OurClient oc = null;

public ClientGUI(String s) {
super(s);

jtaAreaPanel = new JPanel();
jtaAreaPanel.setLayout(new GridLayout(2, 1));

jta = new JTextArea(7, 35);
jta.setLineWrap(true);
jta.setBackground(new Color(169, 255, 128));
JScrollPane jsp = new JScrollPane(jta);

jtaInput = new JTextArea(7, 35);
jtaInput.setLineWrap(true);
jtaInput.setBackground(new Color(133, 168, 250));
jtaInput.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
String s = jtaInput.getText();
jtaInput.setText(null); // 輸入框重新設為空
jta.append("\n" + "你發送了:" + s.trim());
stringGet = s;

if (stringGet != null) {
System.out.println("stringGet:" + stringGet);
try {
oc.getOsw().write(stringGet + "\n");
oc.getOsw().flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
});
JScrollPane jspIn = new JScrollPane(jtaInput);

jtaAreaPanel.add(jsp);
jtaAreaPanel.add(jspIn);

j = new JPanel();

buttonSubmit = new JButton("提交");
buttonSubmit.addActionListener(new SetButtonSubmit());
buttonExit = new JButton("關閉");
buttonExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
j.add(buttonSubmit);
j.add(buttonExit);

setLayout(new BorderLayout());
add(jtaAreaPanel, BorderLayout.CENTER);
add(j, BorderLayout.SOUTH);

setSize(new Dimension(400, 500));
setLocation(500, 300);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);

// 啟動讀取服務端信息線程
new Thread(new ServerOurRead()).start();

oc = new OurClient();
}

public String GetString() {
return stringGet;
}

public void setStringGet(String s) {
this.stringGet = s;
}

class SetButtonSubmit implements ActionListener {
@SuppressWarnings("static-access")
public void actionPerformed(ActionEvent e) {
String s = jtaInput.getText();
jtaInput.setText(null); // 輸入框重新設為空
jta.append("\n" + "你發送了:" + s.trim());
stringGet = s;

if (stringGet != null) {
System.out.println("stringGet:" + stringGet);
try {
oc.getOsw().write(stringGet + "\n");
oc.getOsw().flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}

// 接收來自客戶端的線程
class ServerOurRead implements Runnable {
public void run() {
while (true) {
try {
// oc.getBr().readLine()此方法一直在讀,直到流中有數據
jta.append("\n來自客戶端:" + oc.getBr().readLine());// readLine()
} catch (Exception e1) {
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public static void main(String args[]) {
new ClientGUI("對話框");
}
}

OurClient 類:

import java.io.*;
import java.net.*;
import java.util.*;

public class OurClient {
private Socket socket = null;

private OutputStream os = null;

private InputStream is = null;

private OutputStreamWriter osw = null;

private InputStreamReader isr = null;

private BufferedReader br = null;

private Scanner console = null;

private static String s = null;

private static String In = null;

public OurClient() {
console = new Scanner(System.in);

try {
socket = new Socket("127.0.0.1", 22222);

os = socket.getOutputStream();
is = socket.getInputStream();

osw = new OutputStreamWriter(os);
isr = new InputStreamReader(is);

br = new BufferedReader(isr);

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

// 從服務端讀信息的線程
public BufferedReader getBr() {
return br;
}

public void setBr(BufferedReader br) {
this.br = br;
}

public OutputStreamWriter getOsw() {
return osw;
}

public void setOsw(OutputStreamWriter osw) {
this.osw = osw;
}

public static void main(String args[]) {
}
}

㈣ JAVA 用代碼實現登入QQ空間操作

遼主臨軒的分享
分享

java程序模擬qq登錄界面的代碼

java程序如何實現登錄、記住密碼、自動登錄等功能!

package dyno.swing.beans.qq;

import javax.swing.*;
import javax.swing.event.MouseInputListener;

import org.jvnet.substance.skin.;
/*import org.jvnet.substance.skin.SubstanceModerateLookAndFeel;
import org.jvnet.substance.skin.;*/

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class QQLogin extends JFrame implements MouseInputListener,ActionListener{
JLabel guanggao,beijing,wenzi,she,zhanghaowb,qq1,dengluzhuangtai;
// JTextField zhanghao;

JPopupMenu haoma;
JComboBox zhanghao;
JPasswordField mima;
JCheckBox jizhumima,zidongdenglu;
JButton denglu,chashamuma;
JProgressBar jpb;
SimThread activity;
Timer activityMonitor;
String name,qq;
Socket s;
public QQLogin()
{
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (ClassNotFoundException e1) {
// TODO 自動生成 catch 塊
e1.printStackTrace();
} catch (InstantiationException e1) {
// TODO 自動生成 catch 塊
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO 自動生成 catch 塊
e1.printStackTrace();
} catch ( e1) {
// TODO 自動生成 catch 塊
e1.printStackTrace();
}
chashamuma = new JButton("查殺木馬");
chashamuma.setBounds(240, 155,85, 20);
this.add(chashamuma);
jpb = new JProgressBar();
jpb.setStringPainted(true);
jpb.setBounds(100, 240, 200, 15);
this.add(jpb);
chashamuma.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

jpb.setMaximum(1000);//設置進度欄的最大值
activity=new SimThread(1000);
activity.start();//啟動線程
activityMonitor.start();//啟動定時器
chashamuma.setEnabled(false);//禁止按鈕
}
});
activityMonitor=new Timer(100,new ActionListener(){//每0.5秒執行一次
public void actionPerformed(ActionEvent e){//以下動作將在事件調度線程中運行,十分安全

int current=activity.getCurrent();//得到線程的當前進度

jpb.setValue(current);//更新進度欄的值

if(current==activity.getTarget()){//如果到達目標值
activityMonitor.stop();//終止定時器
chashamuma.setEnabled(true);//激活按鈕
}
}
});
dengluzhuangtai = new JLabel(new ImageIcon("zaixianzhuangtai.jpg"));
dengluzhuangtai.setBounds(75, 145, 35, 30);
this.add(dengluzhuangtai);
dengluzhuangtai.addMouseListener(this);
denglu = new JButton("登錄");
denglu.setBounds(140, 155, 80, 20);
this.add(denglu);
this.setAlwaysOnTop(true);
zidongdenglu = new JCheckBox("自動登錄");
zidongdenglu.setBounds(200, 190, 100, 30);
this.add(zidongdenglu);
jizhumima = new JCheckBox("記住密碼");
jizhumima.setBounds(100, 190, 100, 30);
// jizhumima.setBackground(new Color(228, 244, 255));
this.add(jizhumima);

haoma = new JPopupMenu();

/* zhanghao = new JTextField(20);
zhanghao.setBounds(120, 78, 135, 20);
zhanghao.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.WHITE));
zhanghao.setFont(new Font("宋體",Font.PLAIN,13));
this.add(zhanghao);*/
// zhanghaowb = new JLabel(new ImageIcon("2.png"));
// zhanghaowb.setBounds(90, 73, 194, 31);
// jiantou = new JLabel(new ImageIcon("jiantou.png"));
// jiantou.setBounds(256, 78, 23, 21);
// jiantou.addMouseListener(this);
// this.add(jiantou);
// this.add(zhanghaowb);
chashamuma.addActionListener(this);
mima = new JPasswordField();
mima.setEchoChar('*');
mima.setFont(new Font("宋體",Font.PLAIN,13));
mima.setBounds(100, 113, 150, 20);
this.add(mima);

zhanghao = new JComboBox();
zhanghao.setEditable(true);
zhanghao.setBounds(100, 78, 150, 20);
zhanghao.setFont(new Font("宋體",Font.PLAIN,13));
this.add(zhanghao);
guanggao = new JLabel(new ImageIcon("guanggao.gif"));
guanggao.setBounds(0, 0, 334, 64);
beijing = new JLabel(new ImageIcon("beijing.jpg"));
beijing.setBounds(0, 64, 334, 154);
wenzi = new JLabel(new ImageIcon("wenzi.jpg"));
wenzi.setBounds(30, 75, 50, 100);

denglu.addActionListener(this);
// zhanghaowb.addMouseListener(this);
// zhanghao.addMouseListener(this);
this.add(wenzi);
this.add(beijing);
this.setLayout(null);
this.add(guanggao);
this.setVisible(true);
this.setDefaultCloseOperation(3);
this.setSize(340, 250);
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
/*JFrame.(true);
try {
UIManager.setLookAndFeel(new ()) ;
UIManager.setLookAndFeel("org.jvnet.substance.skin.");

} catch (Exception e) {
System.out.println("Substance Raven Graphite failed to initialize");
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
QQLogin w = new QQLogin();
w.setVisible(true);
}
});*/
new QQLogin();
}
public void mouseClicked(MouseEvent e) {
// TODO 自動生成方法存根

}
public void mouseEntered(MouseEvent e) {
if(e.getSource() == dengluzhuangtai)
{
dengluzhuangtai.setIcon(new ImageIcon("zaixianzhuangtaidian.jpg"));
}

}
public void mouseExited(MouseEvent e) {
if(e.getSource() == dengluzhuangtai)
{
dengluzhuangtai.setIcon(new ImageIcon("zaixianzhuangtai.jpg"));

}

}
public void mousePressed(MouseEvent e) {
// TODO 自動生成方法存根

}
public void mouseReleased(MouseEvent e) {
// TODO 自動生成方法存根

}
public void mouseDragged(MouseEvent e) {
// TODO 自動生成方法存根

}
public void mouseMoved(MouseEvent e) {
// TODO 自動生成方法存根

}
public class liaotianchuangkou
{

}
class SimThread extends Thread{//線程類
private int current;//進度欄的當前值
private int target;//進度欄的最大值

public SimThread(int t){
current=0;
target=t;
}

public int getTarget(){
return target;
}

public int getCurrent(){
return current;
}

public void run(){//線程體
try{
while (current<target && !interrupted()){//如果進度欄的當前值小於目標值並且線程沒有被中斷
sleep(10);
current++;
if(current == 700)
{
sleep(3000);
}
else if(current == 730)
{
sleep(1000);
}
}
}catch (InterruptedException e){}
}

}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == chashamuma)
{
this.setBounds(300, 300, 340, 300);
}
else if(e.getSource() == denglu)
{
String zh = (String) zhanghao.getSelectedItem();
System.out.println(zhanghao.getSelectedItem());
// System.out.println(zhanghao.getItemAt(0));
char [] str = mima.getPassword();
String mima = String.valueOf(str);;
System.out.println(mima);
// Sql login = new Sql();

// if(login.login(zh,mima))
// {
try {
s = new Socket("127.0.0.1",8888);
System.out.println(s);
PrintWriter pw;
Scanner sc;
pw = new PrintWriter(s.getOutputStream(),true);
sc = new Scanner(s.getInputStream());
String str2 = "login#289872400198724#"+zh+"#289872400198724#"+mima;
System.out.println(str2);
pw.println(str2);

String str3 = sc.nextLine();
String yanzheng[] = str3.split("#");
System.out.println(str3);
if(yanzheng[0].equals("true"))
{
System.out.println("登陸成功!");
name = yanzheng[1];
qq = yanzheng[2];

// this.setVisible(false);

// Thread.sleep(5000);
System.out.println("woao"+name);
System.out.println("woai"+qq);

Logined logined = new Logined(name,qq);
this.setVisible(false);

}
else
{
JOptionPane.showMessageDialog(this, "用戶名或密碼錯誤!", "用戶名或密碼錯誤!", 0);
}

} catch (UnknownHostException e2) {
// TODO 自動生成 catch 塊
e2.printStackTrace();
} catch (IOException e2) {
// TODO 自動生成 catch 塊
e2.printStackTrace();
}

/*try {
login.rs = login.stat.executeQuery("select * from qquser where username='"+zh+"' and password = '"+mima+"'");
boolean flag = login.rs.next();
if(flag == true)
{
name = login.rs.getString("name");
qq = login.rs.getString("username");
}
else
{

}*/

// } catch (SQLException e1) {
// TODO 自動生成 catch 塊
// e1.printStackTrace();
// }

}
else
{
JOptionPane.showMessageDialog(this, "用戶名或密碼錯誤", "輸入錯誤", 0);
}
// this.setVisible(false);
//new Logined();

}

}

㈤ java socket 客戶端能 多次 隨時 向客戶端發送會話嗎要怎麼實現,能舉個例子嗎 在線等,謝謝再次謝謝

可以做的到,但這個是有前提的,就好像QQ一樣,必須對方在線,他才能收到你的會話。
比如說多次,你可以採用循環輸入,等到滿足一個條件時,退出!
比如說發送方代碼如下:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

class practise12{
public static void main(String[] args) throws SocketException, UnknownHostException, IOException{
DatagramSocket ds=new DatagramSocket(3000);
DatagramPacket dp=null;
String str="";
do{
System.out.println("請輸入:");
Scanner input=new Scanner(System.in);
str=input.next();
dp=new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("localhost"),8000);
ds.send(dp);
}while(str.compareTo("exit")!=0);
ds.close();
}
}

這樣你就可以多次發送會話,當發送方輸入「exit」時,程序就會退出。
接收方也是同樣道理:當接收到「exit」時,程序退出。

一點灼見,希望對你有用!

閱讀全文

與javasocket仿qq相關的資料

熱點內容
微信上面的圖片看不到 瀏覽:289
基層財務資料庫怎麼建立 瀏覽:262
加密狗檢測工具下載 瀏覽:889
智慧燈app怎麼使用 瀏覽:617
tcl手機升級程序 瀏覽:188
跳出了icloud密碼重置 瀏覽:110
哪裡能查信用卡數據 瀏覽:191
結婚請柬哪個app靠譜 瀏覽:932
qq無法閱讀pdf文件 瀏覽:284
ai導出pdf文件有輪廓線 瀏覽:819
刷機時數據線插台式電腦哪裡 瀏覽:432
手機qq怎樣隱身登陸 瀏覽:339
cdelete導致程序崩潰 瀏覽:783
小米4手機設置鈴聲在哪個文件夾里 瀏覽:184
linuxnet論壇源碼下載 瀏覽:241
手機修改文件後綴名 瀏覽:32
jsvideofullscreen 瀏覽:120
夢幻模擬戰1修改代碼 瀏覽:928
cad有nc編程功能嗎怎麼用 瀏覽:573
js調用外部js 瀏覽:273

友情鏈接