首页
java的Socket 连接
日期:2021-10-25 12:59  点击:269
java的Socket 连接

package chartall;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.*;

import java.sql.*;
import java.util.*;

public class cilent extends JFrame {
private JButton send;//添加发送按钮
private JPanel up;//添加内容为up的面板
private JPanel center;//添加内容为center的面板
private JPanel down;//添加内容为down的面板
private JTextArea inputTextArea;//输入
private JTextArea showTextArea;//显示
private JComboBox userlist;//输入
private JButton serverjoin;//添加按钮serverjoin
private JButton serverjoinsubmit=new JButton("确定");;//将上面的按钮自定义为确定
private JLabel serverjoinlable;//添加内容为serverjoinlable
private JTextField username;//添加用户名文本框
private JTextField ip;//添加ip地址文本框
private JTextField port;//添加端口文本框
private Socket client;//定义client包
private String userid;//用户账号
private InetAddress ips;
private int ports;//端口
cilent(){
gui();//图形界面
listion();//按钮监听
flashuser();//刷新在线人数
}
void gui(){
//窗体
JFrame f=new JFrame("客户端");
f.setSize(800,500);// 设置行高800
f.setLocation(300,100); // 设置每页显示的数目300
up=new JPanel() ;
center=new JPanel() ;
down=new JPanel() ;
inputTextArea=new JTextArea(5,50);//输入文本框大小
showTextArea=new JTextArea(20,50);//显示文本框大小
showTextArea.setEditable(false);
serverjoinlable=new JLabel("未连接服务器") ;
down.add(serverjoinlable);
send=new JButton("发送") ;//按钮名为发送
serverjoin=new JButton("连接服务器") ;
down.add(serverjoin);
userlist=new JComboBox();
userlist.addItem("所有人");
up.add(new JScrollPane(showTextArea));
center.add(inputTextArea);
down.add(userlist);
down.add(send);
f.setLayout(new BorderLayout());
f.add(up,BorderLayout.NORTH);//按钮添加到面板
f.add(center,BorderLayout.CENTER);//按钮添加到面板
f.add(down,BorderLayout.SOUTH);//按钮添加到面板
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);//设为可视
showTextArea.setForeground(new Color(255,177,88));
}
//清屏
//连接服务器监听
void listion() {
//连接服务器监听
serverjoin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog(cilent.this, true );//设置模态对话框
dialog.setLayout(new GridLayout(4,2));//设置布局及参数
dialog.setTitle("服务器连接");
dialog.setSize(300, 200);
dialog.setLocation(50, 50);
JLabel usernametext=new JLabel("用户名");//设置标签
JLabel iptext=new JLabel("IP");//设置标签
JLabel porttext=new JLabel("端口");//设置标签
username=new JTextField();//设置对话栏
ip=new JTextField();//设置对话栏
port=new JTextField();//设置对话栏
dialog.add(usernametext);//组件加入对话框
dialog.add(username);//组件加入对话框
dialog.add(iptext);//组件加入对话框v
dialog.add(ip);//组件加入对话框
dialog.add(porttext);//组件加入对话框
dialog.add(port);//组件加入对话框
dialog.add(serverjoinsubmit);//组件加入对话框
dialog.setVisible(true);//窗体可见
});
//服务器连接输入ip端口并提交
serverjoinsubmit.addActionListener(new ActionListener() { //监听器
public void actionPerformed(ActionEvent e) {
serverjoinlable.setText("已连接服务器");
try {
ips = InetAddress.getByName(ip.getText());
ports=Integer.parseInt(port.getText());
client=new Socket(ips,ports);
//面板 弹出对话框
JOptionPane.showMessageDialog(null, "服务器连接成功!!!!!!", "information", JOptionPane.INFORMATION_MESSAGE);

PrintWriter writer = new PrintWriter(client.getOutputStream());//创建对象
userid=username.getText();//获取username给变量userid
String a=userid+"@@"+"reg";
writer.println(a);
writer.flush();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
//发送聊天内容
send.addActionListener(new ActionListener() { //创建对象
public void actionPerformed(ActionEvent e) {
try {
PrintWriter writer = new PrintWriter(client.getOutputStream());//创建对象
String a=userid+"@"+inputTextArea.getText()+"@"+userlist.getSelectedItem();
writer.println(a);
writer.flush();
//面板 弹出一个对话框
JOptionPane.showMessageDialog(null, "数据发送成功!!!", "information", JOptionPane.INFORMATION_MESSAGE);
//弹出消息
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
//刷新按钮监听
void flashuser(){
new Thread() {//多线程方法
public void run() {//多线程run方法
while(true) { //while死循环
System.out.println(client);
if(client!=null) {//判断是否为空
try {
BufferedReader r = new BufferedReader(new InputStreamReader(client.getInputStream())); //用inputstreamreader中介把system.in字节流换成字符流bufferedreader
String line=r.readLine();
String[] arr=line.split("@");//用@隔开
//null@aaaa@userlist
if(arr[arr.length-1].equals("userlist")) {//判断其末位长度-1是否等于userlist
for(String user:arr) {
if(!user.equals("null")&&!user.equals("userlist")) {
userlist.addItem(user);
}
}
}else if(arr[arr.length-1].equals("群发聊天")) {
showTextArea.append(arr[0]+arr[1]+"\n");
}else {
showTextArea.append(arr[0]+arr[1]+arr[2]+"\n");
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
}.start();
}
//先运行主函数
public static void main(String[] args) {
new cilent();
}

}

====================================================================================================================================================

package chartall;

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class DL extends JFrame{
JTextField txtname=new JTextField(); //用户的文框
JPasswordField txtpass=new JPasswordField(); //密码的文框
JButton bl=new JButton("登录"); //新建一个登陆的按钮
JButton bg=new JButton("关闭"); //新建一个关闭的按钮
public DL(){
setBounds(25,25,250,250);
Container c = getContentPane(); //获取内容面板
c.setLayout(new GridLayout(4,2,10,10)); //布局
this.setResizable(false);
c.add(new JLabel("用户名")); //将用户名添加进去
c.add(txtname); //将用户名框格添加进去
c.add(new JLabel("密码")); //将密码按钮添加进去
c.add(txtpass); //将密码框格添加进去
c.add(bl); //添加按钮b1
c.add(bg); //添加按钮bg
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
//按钮bg的监听
bg.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
}
);
//按钮b1的监听
bl.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String name = txtname.getText();
@SuppressWarnings("deprecation")
String pass = txtpass.getText();
if(name.equals("zwt")&&pass.equals("3721")){ //判断用户名和密码是否符合
System.out.println("登陆成功");
showreguser();
} else{
System.out.println("登录失败");
}
}
}
);
}
public void showreguser() {
new server().setVisible(true); //创建注册页面构造方法对象,窗口可见
}
public static void main(String[] args) {
new DL();
}
}
====================================================================================================================================================


package chartall;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Set;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class server extends JFrame { //设置窗体参数和组件
private JButton serverstart;
private JPanel up;
private JPanel down;
private JLabel serverstartlable;
private JTextField port;
private JButton serversubmit=new JButton("确定启动");
private ServerSocket serversocket;
private HashMap userlist=new HashMap();
private Socket client;
public server() { //设置应用类种方法
gui();//图形界面
listion();//按钮监听
waitsocket();//等待客户端连接
flashchart();//刷新聊天内容
}
void gui(){
//窗体
JFrame f=new JFrame("服务端"); //设置服务端窗体对象f
f.setSize(400,200); //窗体大小
f.setLocation(300,100); //窗体位置
up=new JPanel() ;//设置窗体组件
down=new JPanel() ;
serverstartlable=new JLabel("未启动服务器") ;
up.add(serverstartlable);//将标签加入up窗体组件
serverstart=new JButton("启动服务器") ;
down.add(serverstart);//将标签加入down窗体组件
f.setLayout(new BorderLayout());//设置窗体布局
f.add(up,BorderLayout.NORTH);
f.add(down,BorderLayout.SOUTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true); //设置窗体可见
}
void listion() {
//服务器端口
serverstart.addActionListener(new ActionListener() { //给serverstart设置监听器
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog(server.this, true );
dialog.setTitle("服务器连接端口");
dialog.setSize(300, 200); //大小
dialog.setLocation(50, 50);//位置
dialog.setLayout(new FlowLayout());
JLabel portlable=new JLabel("端口号");
port=new JTextField(10);
dialog.add(portlable);
dialog.add(port);
dialog.add(serversubmit);
dialog.setVisible(true);
}
});
//服务器端口确定
serversubmit.addActionListener(new ActionListener() { //给serversubmit设置监听器
public void actionPerformed(ActionEvent e) {
String a="服务器已启动,端口:"+port.getText();//当serversubit启动时显示提示并获取port内容
serverstartlable.setText(a);
int ports=Integer.parseInt(port.getText());
try {
serversocket=new ServerSocket(ports);
}catch(Exception e1) { //错误反馈
return;
}
}
});
}
//刷新界面
void flashchart(){
new Thread() {
public void run() {
while(true) {
System.out.println(client);
if(client!=null) {
String str;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(client
.getInputStream()));
str=reader.readLine();
}catch(Exception e1) {
return;
}
String[] arr=str.split("@");
String usrename = arr[0];
String message = arr[1];
String status = arr[2];
//zhangshan@@reg
//zhangshan@聊天内容@all
//zhangshan@聊天@wang
if(status.equals("reg")) { //与reg进行判断
Setkeyset=userlist.keySet();
int a=0;
for(String user:keyset) {
if(user.equals(usrename)) {
a=1;
break;
}
}
if(a==0) {
userlist.put(usrename, client);
}
String userflash=null;
for(String user:keyset) {
userflash=userflash+"@"+user;
}
userflash=userflash+"@userlist";
for(String user:keyset) {
try {
PrintWriter writer = new PrintWriter(userlist.get(user).getOutputStream());
//创建writer对象
writer.println(userflash);
writer.flush();
}catch(Exception e1) {
return;
}
}
}else if(status.equals("所有人")) {
Setkeyset=userlist.keySet(); //设置集合类存储数据
for(String user:keyset) {
try {
String allchart=usrename+"@对所有人说:"+message+"@群发聊天";
PrintWriter writer = new PrintWriter(userlist.get(user).getOutputStream());
//创建writer对象
writer.println(allchart);
writer.flush();
}catch(Exception e1) {
return;
}
}
}else{
Setkeyset=userlist.keySet();
for(String user:keyset) { //用foreach循环将keyset的值存入user
try {
if(status.equals(user)) {
String allchart=usrename+"@对"+status+"说:@"+message;
PrintWriter writer = new PrintWriter(userlist.get(user).getOutputStream());
//创建writer对象
writer.println(allchart);
writer.flush();
}
}catch(Exception e1) {
return;
}
}
}
}
}
}
}.start();
}
//等待数据的传输,运行
void waitsocket(){
new Thread() {
public void run() {
while(true) {
System.out.println(serversocket);
if(serversocket!=null) {
try {
client= serversocket.accept();//接口接受的一个连接
}catch(Exception e1) {
return;
}
}
}
}
}.start();
}

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




上一篇· 关于java的InetAddress连接
最新文章
热门文章
关于网站  |  联系我们  |  网站地图  | 
2021-10-25 12:59
Powered by edu63.com
首页 刷新 顶部