给你个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);
//出错,打印出错信息
}
}
}