扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
很久以前做的了,启动程序两次,在单选框中选服务器点连接(一定要先点服务器-连接),在在另外一个界面中选客户端点连接;
专注于为中小企业提供成都网站设计、成都网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业肇庆免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上千多家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class QQ extends JFrame implements ActionListener{
public static void main(String args[]){
QQ qq=new QQ();
}
String input;
ServerSocket ss;
Socket s1,s2;
PrintWriter pw;
BufferedReader br;
private server s;
private client cc;
private JLabel l1,l2,l3,l4,l5;
private JRadioButton jb[]=new JRadioButton[2];
private JTextField jf1,jf2,jf3;
private JButton j1,j2,j3;
private JTextArea ja;
public QQ(){
super("聊天");
Container c=getContentPane();
c.setLayout(null);
l1=new JLabel("TCP通信程序");
l1.setFont(new Font("宋体",Font.BOLD,16));
l1.setBackground(Color.black);
l1.setSize(2000,20);
l1.setLocation(10,10);
c.add(l1);
String str1[]={"服务端","客户端"};
ButtonGroup bg=new ButtonGroup();
for(int x=0;xstr1.length;x++)
{
jb[x]=new JRadioButton(str1[x]);
jb[x].setFont(new Font("宋体",Font.BOLD,15));
jb[x].setForeground(Color.black);
jb[x].setSize(80,40);
jb[x].setLocation(10+x*80,37);
bg.add(jb[x]);
c.add(jb[x]);
}
jb[0].setSelected(true);
l2=new JLabel("连接主机IP");
l2.setFont(new Font("宋体",Font.BOLD,16));
l2.setBackground(Color.black);
l2.setSize(120,20);
l2.setLocation(20, 80);
c.add(l2);
jf1=new JTextField("127.0.0.1");
jf1.setSize(220,30);
jf1.setLocation(120, 80);
c.add(jf1);
jf3=new JTextField("离线");
jf3.setSize(150,30);
jf3.setLocation(280, 40);
c.add(jf3);
l5=new JLabel("连接状态:");
l5.setFont(new Font("宋体",Font.BOLD,16));
l5.setBackground(Color.black);
l5.setSize(120,20);
l5.setLocation(200, 47);
c.add(l5);
j1=new JButton("连接");
j1.setSize(110,20);
j1.setLocation(360,85);
j1.addActionListener(this);
c.add(j1);
l3=new JLabel("接收到的信息");
l3.setFont(new Font("宋体",Font.BOLD,16));
l3.setBackground(Color.black);
l3.setSize(120,20);
l3.setLocation(20, 130);
c.add(l3);
ja=new JTextArea();
ja.setSize(250,200);
ja.setLocation(130, 130);
c.add(ja);
l4=new JLabel("发送信息");
l4.setFont(new Font("宋体",Font.BOLD,16));
l4.setBackground(Color.black);
l4.setSize(120,20);
l4.setLocation(20, 340);
c.add(l4);
jf2=new JTextField("gf");
jf2.setSize(220,30);
jf2.setLocation(120, 340);
c.add(jf2);
j2=new JButton("发送信息");
j2.setSize(110,20);
j2.setLocation(360,350);
j2.addActionListener(this);
c.add(j2);
j3=new JButton("结束连接");
j3.setSize(110,20);
j3.setLocation(360,110);
j3.addActionListener(this);
c.add(j3);
s=new server();
cc=new client();
j3.setEnabled(false);
j2.setEnabled(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,450);
setVisible(true);
setLocation(300,300);
}
public void actionPerformed(ActionEvent e) {
// TODO 自动生成方法存根
if(e.getSource()==j1)
{
try{
if(jb[0].isSelected()==true)
{
input="";
s.start();
}
else {
input="";
cc.start();
}
}
catch(Exception ee)
{
jf3.setText("发生错误");
}
}
if(e.getSource()==j2)
{
pw.write(jf2.getText()+"\n");
pw.flush();
}
if(e.getSource()==j3)
{
try
{
if(jb[0].isSelected()==true)
{ s1.close();
jf3.setText("离线");
j2.setEnabled(false);
j3.setEnabled(false);
}
else
{
s2.close();
jf3.setText("离线");
j2.setEnabled(false);
j3.setEnabled(false);
}
}
catch (Exception e1) {
// TODO 自动生成 catch 块
}
}
}
class server extends Thread{
public void run(){
try {
j1.setEnabled(false);
jf3.setText("正在连接中@");
ss=new ServerSocket(4000);
s1=ss.accept();
br=new BufferedReader(new InputStreamReader(s1.getInputStream()));
pw=new PrintWriter(s1.getOutputStream(),true);
// bs=new BufferedOutputStream(os);
while(true){
if(ss.isBound()==true){
jf3.setText("连接成功");
j2.setEnabled(true);
j3.setEnabled(true);
break;
}
}
while(true)
{
input=br.readLine();
if(input.length()0){
ja.append(input);
ja.append("\n");
}
}
} catch (Exception e) {
// TODO 自动生成 catch 块
}
}
}
class client extends Thread{
public void run(){
try {
j1.setEnabled(false);
jf3.setText("正在连接中@");
s2=new Socket(InetAddress.getByName(jf1.getText()),4000);
// s2=new Socket();
// s2.connect(new InetSocketAddress(jf1.getText(),21),1000);
br=new BufferedReader(new InputStreamReader(s2.getInputStream()));
pw=new PrintWriter(s2.getOutputStream(),true);
// bs=new BufferedOutputStream(os);
while(true){
if(s2.isConnected()==true){
jf3.setText("连接成功");
j2.setEnabled(true);
j3.setEnabled(true);
break;
}
}
input="";
while(true){
input=br.readLine();
if(input.length()0)
{
ja.append(input);
}
}
} catch (Exception e) {
// TODO 自动生成 catch 块
}
}
}
}
/**
* 基于UDP协议的聊天程序
*
* 2007.9.18
* */
//导入包
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
public class Chat extends JFrame implements ActionListener
{
//广播地址或者对方的地址
public static final String sendIP = "172.18.8.255";
//发送端口9527
public static final int sendPort = 9527;
JPanel p = new JPanel();
List lst = new List(); //消息显示
JTextField txtIP = new JTextField(18); //填写IP地址
JTextField txtMSG = new JTextField(20); //填写发送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("发送");
byte [] buf;
//定义DatagramSocket的对象必须进行异常处理
//发送和接收数据报包的套接字
DatagramSocket ds = null;
//=============构造函数=====================
public Chat()
{
CreateInterFace();
//注册消息框监听器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);
try
{
//端口:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//============接受消息============
//匿名类
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024];
//表示接受数据报包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add("【消息来自】◆" + dp.getAddress().getHostAddress() + "◆"+"【说】:" + new String (buf,0,dp.getLength()) /*+ dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();
//关闭窗体事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println("test");
int n=JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
dispose();
System.exit(0);
ds.close();//关闭ds对象//关闭数据报套接字
}
}
});
}
//界面设计布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER);
this.add(p,BorderLayout.SOUTH);
p.add(lblIP);
p.add(txtIP);
p.add(lblMSG);
p.add(txtMSG);
p.add(btnSend);
txtIP.setText(sendIP);
//背景颜色
lst.setBackground(Color.yellow);
//JAVA默认风格
this.setUndecorated(true);
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
this.setSize(600,500);
this.setTitle("〓聊天室〓");
this.setResizable(false);//不能改变窗体大小
this.setLocationRelativeTo(null);//窗体居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦点
}
//===============================Main函数===============================
public static void main(String[]args)
{
new Chat();
}
//================================发送消息===============================
//消息框回车发送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本内容
buf = txtMSG.getText().getBytes();
//判断消息框是否为空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"发送消息不能为空","提示",JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText("");//清空消息框
//点发送按钮发送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
txtMSG.setText("");//清空消息框
txtMSG.requestFocus();
}
}
}
客户端源代码
import java.net.Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class socketClient
{
private DataOutputStream output;
private DataInputStream input;
private String clientName;
public static void main(String[] args)
{
//在main函数中,启动服务器的socket
new socketClient().ConnectServer();
}
public void ConnectServer()
{
try
{
Socket socket = new Socket("127.0.0.1",10001);
clientName = socket.getInetAddress().toString();
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
new readServer().start();
new writeServer().start();
}
catch(Exception e) {System.out.println(e.toString());}
}
public class readServer extends Thread
{
private Socket client;
public void run()
{
String msg;
try
{
while(true)
{
msg = input.readUTF();
if(msg!=null)
System.out.println("收到消息:【"+clientName+"】 "+msg);
}
}
catch(Exception e) {System.out.println(e.toString());}
}
}
public class writeServer extends Thread
{
private Socket client;
public void run()
{
try
{
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while(true)
{
if(stdIn.ready())
{
userInput = stdIn.readLine();
if(userInput!="exit")
{
output.writeUTF(userInput);
System.out.println("已发送消息给【"+clientName+"】"+userInput);
}
}
}
}
catch(Exception e) {System.out.println(e.toString());}
}
}
}
服务器源代码
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class socketServer
{
ArrayList clientList = new ArrayList();
//private DataOutputStream output;
//private DataInputStream input;
//private String clientName;
//private Socket socket;
public static void main(String[] args)
{
//在main函数中,启动服务器的socket
new socketServer().OpenServer();
}
public void OpenServer()
{
try
{
ServerSocket server = new ServerSocket(10001);
Socket socket;
while((socket = server.accept())!=null)
{
clientList.add(socket);
//clientName = socket.getInetAddress().toString();
//output = new DataOutputStream(socket.getOutputStream());
//input = new DataInputStream(socket.getInputStream());
new readClient(socket).start();
new writeClient(socket).start();
}
}
catch(Exception e) {System.out.println(e.toString());}
}
public class readClient extends Thread
{
private Socket socket;
public readClient(Socket client)
{socket = client;}
public void run()
{
String msg;
try
{
String clientName = socket.getInetAddress().toString();
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
DataInputStream input = new DataInputStream(socket.getInputStream());
while((msg = input.readUTF())!=null)
{
System.out.println("收到消息:【"+clientName+"】 "+msg);
}
}
catch(Exception e){System.out.println(e.toString());}
}
}
public class writeClient extends Thread
{
private Socket socket;
public writeClient(Socket client)
{socket = client;}
public void run()
{
try{
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
String clientName = socket.getInetAddress().toString();
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
DataInputStream input = new DataInputStream(socket.getInputStream());
while(true)
{
if(stdIn.ready())
{
userInput = stdIn.readLine();
if(userInput!="exit")
{
output.writeUTF(userInput);
System.out.println("已发送消息给【"+clientName+"】"+userInput);
}
}
}
}
catch(Exception e) {System.out.println(e.toString());}
}
}
}
代码如下:
package com.neusoft.edu.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务器端代码
* 获取客户端发送的信息,显示并且返回对应的回复
* 1、创建ServerSocket对象
* 2、调用accept方法获取客户端连接
* 3、使用输入流读取客户端发送的数据
* 4、使用输出流向客户端写入数据
* 5、关闭对应的对象
* @author L
*
*/
public class ChatServer {
/**
* @param args
*/
public static void main(String[] args) {
try {
//1、创建ServerSocket对象,8875为自定义端口号
ServerSocket server = new ServerSocket(8857);
//简单提示
System.out.println("等待客户端连接……");
//2、获取客户端连接
Socket client = server.accept();
//获取客户端的相关信息
System.out.println(client.getInetAddress().getHostAddress() + "连接上来了……");
//3.1、定义输入流和输出流对象
BufferedReader in = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
//用来获取从控制台输入的数据,将该数据发送给客户端
BufferedReader inByServer = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
//读取到的数据
String data = null;
String answer = null;
//循环和客户端进行通信
do
{
//3.2、读取客户端发送的数据
data = in.readLine();
//在服务器端显示读取到的数据
System.out.println("客户端发送信息:" + data);
//获取服务器端要发送给客户端的信息
System.out.print("服务器端回复客户端:");
answer = inByServer.readLine();
//3.3、将数据写入到客户端
out.println(answer);
out.flush();
}while(!"bye".equals(data));
//4、关闭相关资源
out.flush();
in.close();
inByServer.close();
out.close();
//关闭Socket对象
client.close();
server.close();
System.out.println("服务器端关闭……");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流