很久以前做的了,啟動(dòng)程序兩次,在單選框中選服務(wù)器點(diǎn)連接(一定要先點(diǎn)服務(wù)器-連接),在在另外一個(gè)界面中選客戶端點(diǎn)連接;

專(zhuān)注于為中小企業(yè)提供成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)肇慶免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了上千多家企業(yè)的穩(wěn)健成長(zhǎng),幫助中小企業(yè)通過(guò)網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
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[]={"服務(wù)端","客戶端"};
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("連接主機(jī)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("連接狀態(tài):");
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("發(fā)送信息");
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("發(fā)送信息");
j2.setSize(110,20);
j2.setLocation(360,350);
j2.addActionListener(this);
c.add(j2);
j3=new JButton("結(jié)束連接");
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 自動(dòng)生成方法存根
if(e.getSource()==j1)
{
try{
if(jb[0].isSelected()==true)
{
input="";
s.start();
}
else {
input="";
cc.start();
}
}
catch(Exception ee)
{
jf3.setText("發(fā)生錯(cuò)誤");
}
}
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 自動(dòng)生成 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 自動(dòng)生成 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 自動(dòng)生成 catch 塊
}
}
}
}
/**
* 基于UDP協(xié)議的聊天程序
*
* 2007.9.18
* */
//導(dǎo)入包
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
{
//廣播地址或者對(duì)方的地址
public static final String sendIP = "172.18.8.255";
//發(fā)送端口9527
public static final int sendPort = 9527;
JPanel p = new JPanel();
List lst = new List(); //消息顯示
JTextField txtIP = new JTextField(18); //填寫(xiě)IP地址
JTextField txtMSG = new JTextField(20); //填寫(xiě)發(fā)送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("發(fā)送");
byte [] buf;
//定義DatagramSocket的對(duì)象必須進(jìn)行異常處理
//發(fā)送和接收數(shù)據(jù)報(bào)包的套接字
DatagramSocket ds = null;
//=============構(gòu)造函數(shù)=====================
public Chat()
{
CreateInterFace();
//注冊(cè)消息框監(jiān)聽(tīng)器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);
try
{
//端口:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//============接受消息============
//匿名類(lèi)
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024];
//表示接受數(shù)據(jù)報(bào)包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add("【消息來(lái)自】◆" + dp.getAddress().getHostAddress() + "◆"+"【說(shuō)】:" + new String (buf,0,dp.getLength()) /*+ dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();
//關(guān)閉窗體事件
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();//關(guān)閉ds對(duì)象//關(guān)閉數(shù)據(jù)報(bào)套接字
}
}
});
}
//界面設(shè)計(jì)布局
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默認(rèn)風(fēng)格
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();//消息框得到焦點(diǎn)
}
//===============================Main函數(shù)===============================
public static void main(String[]args)
{
new Chat();
}
//================================發(fā)送消息===============================
//消息框回車(chē)發(fā)送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本內(nèi)容
buf = txtMSG.getText().getBytes();
//判斷消息框是否為空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"發(fā)送消息不能為空","提示",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("");//清空消息框
//點(diǎn)發(fā)送按鈕發(fā)送消息事件
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函數(shù)中,啟動(dòng)服務(wù)器的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("已發(fā)送消息給【"+clientName+"】"+userInput);
}
}
}
}
catch(Exception e) {System.out.println(e.toString());}
}
}
}
服務(wù)器源代碼
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函數(shù)中,啟動(dòng)服務(wù)器的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("已發(fā)送消息給【"+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;
/**
* 服務(wù)器端代碼
* 獲取客戶端發(fā)送的信息,顯示并且返回對(duì)應(yīng)的回復(fù)
* 1、創(chuàng)建ServerSocket對(duì)象
* 2、調(diào)用accept方法獲取客戶端連接
* 3、使用輸入流讀取客戶端發(fā)送的數(shù)據(jù)
* 4、使用輸出流向客戶端寫(xiě)入數(shù)據(jù)
* 5、關(guān)閉對(duì)應(yīng)的對(duì)象
* @author L
*
*/
public class ChatServer {
/**
* @param args
*/
public static void main(String[] args) {
try {
//1、創(chuàng)建ServerSocket對(duì)象,8875為自定義端口號(hào)
ServerSocket server = new ServerSocket(8857);
//簡(jiǎn)單提示
System.out.println("等待客戶端連接……");
//2、獲取客戶端連接
Socket client = server.accept();
//獲取客戶端的相關(guān)信息
System.out.println(client.getInetAddress().getHostAddress() + "連接上來(lái)了……");
//3.1、定義輸入流和輸出流對(duì)象
BufferedReader in = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
//用來(lái)獲取從控制臺(tái)輸入的數(shù)據(jù),將該數(shù)據(jù)發(fā)送給客戶端
BufferedReader inByServer = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
//讀取到的數(shù)據(jù)
String data = null;
String answer = null;
//循環(huán)和客戶端進(jìn)行通信
do
{
//3.2、讀取客戶端發(fā)送的數(shù)據(jù)
data = in.readLine();
//在服務(wù)器端顯示讀取到的數(shù)據(jù)
System.out.println("客戶端發(fā)送信息:" + data);
//獲取服務(wù)器端要發(fā)送給客戶端的信息
System.out.print("服務(wù)器端回復(fù)客戶端:");
answer = inByServer.readLine();
//3.3、將數(shù)據(jù)寫(xiě)入到客戶端
out.println(answer);
out.flush();
}while(!"bye".equals(data));
//4、關(guān)閉相關(guān)資源
out.flush();
in.close();
inByServer.close();
out.close();
//關(guān)閉Socket對(duì)象
client.close();
server.close();
System.out.println("服務(wù)器端關(guān)閉……");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
本文標(biāo)題:聊天通訊java源代碼 聊天室java 代碼
當(dāng)前URL:http://www.yijiale78.com/article12/hhcjdc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化、搜索引擎優(yōu)化、網(wǎng)站制作、云服務(wù)器、外貿(mào)建站、標(biāo)簽優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容