給你個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[]) {
}
}
2. 急急急,在線等Java編程高手來,在聊天室中如何實現發送消息和顯示聊天消息內容,我只寫了框架,如下
你這根本什麼都沒寫啊,原來寫了個模擬QQ的,不過沒去畫界面,供你參考下,希望能幫到你,主要的是你把原理弄清楚就應該沒問題了
伺服器:
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Scanner;
import java.util.regex.*;
public class Server
{
/**
* @param args
*/
private int count = 0;
private int num = 0;
HashMap<Integer,Socket> clients = new HashMap<Integer,Socket>();
public Server()
{
try
{
ServerSocket server = new ServerSocket(33333);
while(true)
{
Socket fromClient = server.accept();
count++;
num++;
clients.put(count, fromClient);
new Thread()
{
public void run()
{
receive();
}
}.start();
new Thread()
{
public void run()
{
send();
}
}.start();
}
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void receive()
{
try
{
BufferedReader read = new BufferedReader(new InputStreamReader(clients.get(count).getInputStream()));
int tmp = count;
int temp = 0;
while(true)
{
String value = "";
try
{
value = read.readLine();
String regex = "^ *~ *(\\d+) *:(.*)";
Pattern pat = Pattern.compile(regex);
Matcher match = pat.matcher(value);
if(match.find())
{
temp = Integer.valueOf(match.group(1));
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(clients.get(temp).getOutputStream()));
write.write("用戶"+tmp+":"+match.group(2)+"\n");
write.flush();
}
else
{
for(int i = 1;i<=num;i++)
{
if(i == tmp)
{
continue;
}
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(clients.get(i).getOutputStream()));
write.write("用戶"+tmp+":"+value + "\n");
write.flush();
}
}
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch(IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public void send()
{
Scanner scan = new Scanner(System.in);
String tmp = "";
while(!tmp.equals("exit"))
{
tmp = scan.nextLine();
try
{
for(int i = 1;i<=num;i++)
{
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(clients.get(i).getOutputStream()));
write.write("系統:"+tmp + "\n");
write.flush();
}
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
new Server();
}
}
客戶端:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client
{
/**
* @param args
*/
BufferedReader read;
BufferedWriter write;
public Client()
{
try
{
Socket client = new Socket("192.168.1.7",33333);
read = new BufferedReader(new InputStreamReader(client.getInputStream()));
write = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
new Thread()
{
public void run()
{
recieve();
}
}.start();
new Thread()
{
public void run()
{
send();
}
}.start();
//send();
}
catch(UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void send()
{
Scanner scan = new Scanner(System.in);
String tmp = "";
while(!tmp.equals("exit"))
{
tmp = scan.nextLine();
try
{
tmp= tmp+"\n";
write.write(tmp);
write.flush();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
void recieve()
{
while(true)
{
try
{
String value = "";
value = read.readLine();
System.out.println(value);
write.flush();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
new Client();
}
}
3. 用JAVA怎麼寫QQ
用java是可以寫出qq的,只不過用java開發c/s的軟體不是java特長的,你要是真的想寫,就寫著練練手吧,最起碼可以鞏固java se上的知識。
具體怎麼寫,給你個大概的思路吧,因為我沒辦法在這個有限的輸入框內把所有的代碼寫完。
【1】先寫出qq的簡單界面
【2】給每個按鈕添加監聽
【3】按鈕事件(方法)定義
【4】連接網路(socket)
【5】測試
【5】其他功能添加
【6】測試
4. 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();
}
}
5. 怎樣有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.);
}
6. 如何使用java socket來傳輸自定義的數據包
以下分四點進行描述:
1,什麼是Socket
網路上的兩個程序通過一個雙向的通訊連接實現數據的交換,這個雙向鏈路的一端稱為一個Socket。Socket通常用來實現客戶方和服務方的連接。Socket是TCP/IP協議的一個十分流行的編程界面,一個Socket由一個IP地址和一個埠號唯一確定。
但是,Socket所支持的協議種類也不光TCP/IP一種,因此兩者之間是沒有必然聯系的。在Java環境下,Socket編程主要是指基於TCP/IP協議的網路編程。
2,Socket通訊的過程
Server端Listen(監聽)某個埠是否有連接請求,Client端向Server 端發出Connect(連接)請求,Server端向Client端發回Accept(接受)消息。一個連接就建立起來了。Server端和Client 端都可以通過Send,Write等方法與對方通信。
對於一個功能齊全的Socket,都要包含以下基本結構,其工作過程包含以下四個基本的步驟:
(1) 創建Socket;
(2) 打開連接到Socket的輸入/出流;
(3) 按照一定的協議對Socket進行讀/寫操作;
(4) 關閉Socket.(在實際應用中,並未使用到顯示的close,雖然很多文章都推薦如此,不過在我的程序中,可能因為程序本身比較簡單,要求不高,所以並未造成什麼影響。)
3,創建Socket
創建Socket
java在包java.net中提供了兩個類Socket和ServerSocket,分別用來表示雙向連接的客戶端和服務端。這是兩個封裝得非常好的類,使用很方便。其構造方法如下:
Socket(InetAddress address, int port);
Socket(InetAddress address, int port, boolean stream);
Socket(String host, int prot);
Socket(String host, int prot, boolean stream);
Socket(SocketImpl impl)
Socket(String host, int port, InetAddress localAddr, int localPort)
Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
ServerSocket(int port);
ServerSocket(int port, int backlog);
ServerSocket(int port, int backlog, InetAddress bindAddr)
其中address、host和port分別是雙向連接中另一方的IP地址、主機名和端 口號,stream指明socket是流socket還是數據報socket,localPort表示本地主機的埠號,localAddr和 bindAddr是本地機器的地址(ServerSocket的主機地址),impl是socket的父類,既可以用來創建serverSocket又可 以用來創建Socket。count則表示服務端所能支持的最大連接數。例如:學習視頻網 http://www.xxspw.com
Socket client = new Socket("127.0.01.", 80);
ServerSocket server = new ServerSocket(80);
注意,在選擇埠時,必須小心。每一個埠提供一種特定的服務,只有給出正確的埠,才 能獲得相應的服務。0~1023的埠號為系統所保留,例如http服務的埠號為80,telnet服務的埠號為21,ftp服務的埠號為23, 所以我們在選擇埠號時,最好選擇一個大於1023的數以防止發生沖突。
在創建socket時如果發生錯誤,將產生IOException,在程序中必須對之作出處理。所以在創建Socket或ServerSocket是必須捕獲或拋出例外。
4,簡單的Client/Server程序
1. 客戶端程序
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try{
Socket socket=new Socket("127.0.0.1",4700);
//向本機的4700埠發出客戶請求
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由系統標准輸入設備構造BufferedReader對象
PrintWriter os=new PrintWriter(socket.getOutputStream());
//由Socket對象得到輸出流,並構造PrintWriter對象
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket對象得到輸入流,並構造相應的BufferedReader對象
String readline;
readline=sin.readLine(); //從系統標准輸入讀入一字元串
while(!readline.equals("bye")){
//若從標准輸入讀入的字元串為 "bye"則停止循環
os.println(readline);
//將從系統標准輸入讀入的字元串輸出到Server
os.flush();
//刷新輸出流,使Server馬上收到該字元串
System.out.println("Client:"+readline);
//在系統標准輸出上列印讀入的字元串
System.out.println("Server:"+is.readLine());
//從Server讀入一字元串,並列印到標准輸出上
readline=sin.readLine(); //從系統標准輸入讀入一字元串
} //繼續循環
os.close(); //關閉Socket輸出流
is.close(); //關閉Socket輸入流
socket.close(); //關閉Socket
}catch(Exception e) {
System.out.println("Error"+e); //出錯,則列印出錯信息
}
}
}
2. 伺服器端程序
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer{
public static void main(String args[]) {
try{
ServerSocket server=null;
try{
server=new ServerSocket(4700);
//創建一個ServerSocket在埠4700監聽客戶請求
}catch(Exception e) {
System.out.println("can not listen to:"+e);
//出錯,列印出錯信息
}
Socket socket=null;
try{
socket=server.accept();
//使用accept()阻塞等待客戶請求,有客戶
//請求到來則產生一個Socket對象,並繼續執行
}catch(Exception e) {
System.out.println("Error."+e);
//出錯,列印出錯信息
}
String line;
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket對象得到輸入流,並構造相應的BufferedReader對象
PrintWriter os=newPrintWriter(socket.getOutputStream());
//由Socket對象得到輸出流,並構造PrintWriter對象
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由系統標准輸入設備構造BufferedReader對象
System.out.println("Client:"+is.readLine());
//在標准輸出上列印從客戶端讀入的字元串
line=sin.readLine();
//從標准輸入讀入一字元串
while(!line.equals("bye")){
//如果該字元串為 "bye",則停止循環
os.println(line);
//向客戶端輸出該字元串
os.flush();
//刷新輸出流,使Client馬上收到該字元串
System.out.println("Server:"+line);
//在系統標准輸出上列印讀入的字元串
System.out.println("Client:"+is.readLine());
//從Client讀入一字元串,並列印到標准輸出上
line=sin.readLine();
//從系統標准輸入讀入一字元串
} //繼續循環
os.close(); //關閉Socket輸出流
is.close(); //關閉Socket輸入流
socket.close(); //關閉Socket
server.close(); //關閉ServerSocket
}catch(Exception e){
System.out.println("Error:"+e);
//出錯,列印出錯信息
}
}
}