/**
專業(yè)領(lǐng)域包括成都做網(wǎng)站、網(wǎng)站設(shè)計(jì)、商城網(wǎng)站開發(fā)、微信營(yíng)銷、系統(tǒng)平臺(tái)開發(fā), 與其他網(wǎng)站設(shè)計(jì)及系統(tǒng)開發(fā)公司不同,創(chuàng)新互聯(lián)的整合解決方案結(jié)合了幫做網(wǎng)絡(luò)品牌建設(shè)經(jīng)驗(yàn)和互聯(lián)網(wǎng)整合營(yíng)銷的理念,并將策略和執(zhí)行緊密結(jié)合,為客戶提供全網(wǎng)互聯(lián)網(wǎng)整合方案。
* 基于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); //填寫IP地址
JTextField txtMSG = new JTextField(20); //填寫發(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)聽器
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];
//表示接受數(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ā)送消息===============================
//消息框回車發(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.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class AddList {
private String filePath = "";
private String bakPath = "";
private String content = "";
Scanner sc = new Scanner(System.in);
public String readFile(){
content = "";
if (isNull(filePath)) {
System.out.println("文件存儲(chǔ)路徑:");
filePath = sc.nextLine();
}
File file = new File(filePath);
FileReader fr = null;
try {
if (file.exists()) {
fr = new FileReader(file);
char[] chars = new char[1024];
int n = 0;
while((n = fr.read(chars)) != -1){
String string = new String(chars, 0, n);
content = content + string;
}
} else {
System.out.println("文件不存在");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
public void writeFile(String path){
File file = new File(path);
FileOutputStream fos = null;
mkDirs(path);
try {
fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
PrintWriter pw = new PrintWriter(bos, true);
pw.print(content);
pw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void writeFile(){
if (isNull(filePath)) {
System.out.println("文件存儲(chǔ)路徑:");
filePath = sc.nextLine();
}
File file = new File(filePath);
FileOutputStream fos = null;
mkDirs(filePath);
try {
fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
PrintWriter pw = new PrintWriter(bos, true);
pw.print(content);
pw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void mkDirs(String filepath){
if (filepath.indexOf("\\") != -1) {
filepath = filepath.replaceAll("\\", "/");
}
int n = filepath.indexOf("http://");
String path = filepath.substring(0, n) + "http://";
filepath = filepath.substring(filepath.indexOf("http://") + 1, filepath.length());
String[] files = filepath.split("/");
for (int i = 0; i files.length - 1; i++) {
path = path + files[i];
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
}
}
public void addImfor(){
System.out.println("--------增加記錄---------");
String name = "";
String tel = "";
String email = "";
content = readFile();
while(true){
System.out.println("姓名:");
name = sc.next();
System.out.println("電話:");
tel = sc.next();
System.out.println("Email:");
email = sc.next();
content = content + name + "" + tel + "" + email +"==";
System.out.println("0、Exit 1、繼續(xù)");
int i = sc.nextInt();
if (i == 0) {
break;
}
}
writeFile();
}
public void deleteImfor(){
System.out.println("---------刪除記錄---------");
String name = "";
String[] imfors = null;
content = readFile();
while(true){
System.out.println("你要?jiǎng)h除的姓名是:");
name = sc.next();
if (content.indexOf(name) != -1) {
imfors = content.split("==");
for (int i = 0; i imfors.length; i++) {
if (imfors[i].indexOf(name) != -1) {
imfors[i] = "";
}
}
具體方法如下:
1、定義封裝一條記錄的實(shí)體類
2、根據(jù)實(shí)際系統(tǒng)容量,定義一個(gè)數(shù)組
3、完成系統(tǒng)中顯示全部記錄的邏輯
4、完成系統(tǒng)中添加一條記錄的邏輯
5、完成系統(tǒng)中刪除一條記錄的邏輯
6、完成系統(tǒng)中修改一條記錄的邏輯
7、全部代碼:
import java.util.Scanner;
class Contact {
String cellPhone;
String name;
}
public class Main {
private static void menu () {
System.out.println("************** 菜單 ******"
+ "************");
System.out.println(" 1.顯示全部通訊錄");
System.out.println(" 2.增加一條記錄");
System.out.println(" 3.刪除一條記錄");
System.out.println(" 4.修改一條記錄");
System.out.println(" 0.退出");
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
Contact[] contacts = new Contact[200];
int size = 0;
String cmd = "";
do {
menu();
System.out.print("請(qǐng)輸入你得選擇:(0-4)");
cmd = scn.nextLine();
if (cmd.equals("1")) {
if (size == 0)
System.out.println("系統(tǒng)當(dāng)前無(wú)記錄!");
else
for (int i = 0; i size; i++) {
System.out.println(contacts[i].name + ":"
+ contacts[i].cellPhone);
}
} else if (cmd.equals("2")) {
System.out.print("請(qǐng)輸入手機(jī)號(hào):");
String cellphone = scn.nextLine();
System.out.print("請(qǐng)輸入姓名:");
String name = scn.nextLine();
Contact contact = new Contact();
contact.cellPhone = cellphone;
contact.name = name;
if (size contacts.length) {
contacts[size++] = contact;
System.out.println("添加成功!");
} else {
System.out.println("你最多只能添加" +
contacts.length + "條記錄");
}
} else if (cmd.equals("3")) {
System.out.print("請(qǐng)輸入要?jiǎng)h除的手機(jī)號(hào):");
String cellphone = scn.nextLine();
int index = -1;
for (int i = 0; i size i contacts.length;
i++) {
if (contacts[i].cellPhone.equals(cellphone)) {
index = i;
break;
}
}
if (index == -1) {
System.out.println("該記錄不存在!");
} else {
for (int i = index; i size; i++) {
contacts[index] = contacts[index + 1];
}
contacts[size - 1] = null;
size--;
System.out.println("刪除成功!");
}
} else if (cmd.equals("4")) {
System.out.print("請(qǐng)輸入要修改的手機(jī)號(hào):");
String cellphone = scn.nextLine();
int index = -1;
for (int i = 0; i size i contacts.length;
i++) {
if (contacts[i].cellPhone.equals(cellphone)) {
index = i;
break;
}
}
if (index == -1) {
System.out.println("該記錄不存在!");
} else {
System.out.print("請(qǐng)輸入姓名:");
String name = scn.nextLine();
contacts[index].name = name;
}
}
} while (!cmd.equals("0"));
System.out.println("退出成功!");
scn.close();
System.exit(0);
}
}
20分?。。???(⊙o⊙)
給你這個(gè)做參考吧。自己改一下就行了。(共兩個(gè)文件)
//ChatClient.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
/*
try {
bConnected = false;
tRecv.join();
} catch(InterruptedException e) {
e.printStackTrace();
} finally {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
//taContent.setText(str);
tfTxt.setText("");
try {
//System.out.println(s);
dos.writeUTF(str);
dos.flush();
//dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
//System.out.println(str);
taContent.setText(taContent.getText() + str + '\n');
}
} catch (SocketException e) {
System.out.println("退出了,bye!");
} catch (EOFException e) {
System.out.println("推出了,bye - bye!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//ChatServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
ListClient clients = new ArrayListClient();
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.out.println("端口使用中....");
System.out.println("請(qǐng)關(guān)掉相關(guān)程序并重新運(yùn)行服務(wù)器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
try {
while(started) {
Socket s = ss.accept();
Client c = new Client(s);
System.out.println("a client connected!");
new Thread(c).start();
clients.add(c);
//dis.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("對(duì)方退出了!我從List里面去掉了!");
//e.printStackTrace();
}
}
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
System.out.println(str);
for(int i=0; iclients.size(); i++) {
Client c = clients.get(i);
c.send(str);
//System.out.println(" a string send !");
}
/*
for(IteratorClient it = clients.iterator(); it.hasNext(); ) {
Client c = it.next();
c.send(str);
}
*/
/*
IteratorClient it = clients.iterator();
while(it.hasNext()) {
Client c = it.next();
c.send(str);
}
*/
}
} catch (EOFException e) {
System.out.println("Client closed!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dis != null) dis.close();
if(dos != null) dos.close();
if(s != null) {
s.close();
//s = null;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
public static void process() {
try {
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements())
{
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)//如果端口類型是串口則判斷名稱
{
if(portId.getName().equals("COM1")){//如果是COM1端口則退出循環(huán)
break;
}else{
portId=null;
}
}
}
SerialPort serialPort = (SerialPort)portId.open("Serial_Communication", 1000);//打開串口的超時(shí)時(shí)間為1000ms
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);//設(shè)置串口速率為9600,數(shù)據(jù)位8位,停止位1們,奇偶校驗(yàn)無(wú)
InputStream in = serialPort.getInputStream();//得到輸入流
OutputStream out = serialPort.getOutputStream();//得到輸出流
//進(jìn)行輸入輸出操作
//操作結(jié)束后
in.close();
out.close();
serialPort.close();//關(guān)閉串口
} catch (PortInUseException e) {
e.printStackTrace();
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
這里有一個(gè)簡(jiǎn)單的模擬通訊 要先運(yùn)行服務(wù)器端 再運(yùn)行客戶端 否則會(huì)報(bào)錯(cuò):
服務(wù)器端代碼:
package?com.test3;
import?java.net.*;
import?java.io.*;
import?javax.swing.*;
import?java.awt.*;
import?java.awt.event.*;
public?class?Server2?extends?JFrame?implements?ActionListener?,?KeyListener?{
JTextArea?jta=null;
JScrollPane?jsp=null;
JTextField?jtf=null;
JButton?jb=null;
JPanel?jp=null;
InputStreamReader?isr=null;
BufferedReader?br=null;
PrintWriter?pw=null;
Socket?s;
String?jtatext="";
public?static?void?main(String[]?args)?{
//?TODO?Auto-generated?method?stub
Server2?sv2=new?Server2();
}
public?Server2(){
jta=new?JTextArea();
jta.setEditable(false);
jsp=new?JScrollPane(jta);
jtf=new?JTextField(10);
jtf.addKeyListener(this);
jb=new?JButton("發(fā)送");
jb.addActionListener(this);
jp=new?JPanel();
jp.add(jtf);
jp.add(jb);
this.add(jsp,"Center");
this.add(jp,"South");
this.setSize(300,300);
this.setLocationRelativeTo(this);
this.setTitle("服務(wù)器端");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
try{
ServerSocket?ss=new?ServerSocket(9999);
s=ss.accept();
isr=new?InputStreamReader(s.getInputStream());
br=new?BufferedReader(isr);
pw=new?PrintWriter(s.getOutputStream(),true);
while(true){
String?info=br.readLine();
jta.append("客戶端對(duì)服務(wù)器說(shuō):???"+info+"\r\n");
// this.jta.setText(jtatext);
}
}catch(Exception?e){
e.printStackTrace();
}
}
@Override
public?void?actionPerformed(ActionEvent?e)?{
if(e.getSource()==jb){
try?{
pw.println(jtf.getText());
jta.append("服務(wù)器對(duì)客戶端說(shuō):???"+jtf.getText()+"\r\n");
// jta.setText(jtatext);
jtf.setText("");
}?catch?(Exception?e1)?{
//?TODO?Auto-generated?catch?block
e1.printStackTrace();
}
}
}
@Override
public?void?keyTyped(KeyEvent?e)?{}
@Override
public?void?keyPressed(KeyEvent?e)?{
if(e.getKeyCode()==KeyEvent.VK_ENTER){
try?{
pw.println(jtf.getText());
jta.append("服務(wù)器對(duì)客戶端說(shuō):???"+jtf.getText()+"\r\n");
jtf.setText("");
}?catch?(Exception?e1)?{
e1.printStackTrace();
}
}
}
@Override
public?void?keyReleased(KeyEvent?e)?{}
}
客戶端代碼:
package?com.test3;
import?java.net.*;
import?java.io.*;
import?javax.swing.*;
import?java.awt.*;
import?java.awt.event.*;
public?class?Client2?extends?JFrame?implements?ActionListener?,KeyListener?{
JTextArea?jta=null;
JScrollPane?jsp=null;
JTextField?jtf=null;
JButton?jb=null;
JPanel?jp=null;
String?jtatext="";
Socket?s;
PrintWriter?pw=null;
InputStreamReader?isr=null;
BufferedReader?br=null;
public?static?void?main(String[]?args)?{
//?TODO?Auto-generated?method?stub
Client2?sv2=new?Client2();
}
public?Client2(){
jta=new?JTextArea();
jta.setEditable(false);
jsp=new?JScrollPane(jta);
jtf=new?JTextField(10);
jtf.addKeyListener(this);
jb=new?JButton("發(fā)送");
jb.addActionListener(this);
jp=new?JPanel();
jp.add(jtf);
jp.add(jb);
this.add(jsp,"Center");
this.add(jp,"South");
this.setSize(300,300);
this.setLocationRelativeTo(this);
this.setTitle("客戶端");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
try?{
?s=new?Socket("127.3.3.3",9999);
?isr=new?InputStreamReader(s.getInputStream());
?br=new?BufferedReader(isr);
?pw=new?PrintWriter(s.getOutputStream(),true);
?
?while(true){
?String?info=br.readLine();?
jta.append("服務(wù)器對(duì)客戶端說(shuō):???"+info+"\r\n");
?
?}
}?catch?(Exception?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
}
@Override
public?void?actionPerformed(ActionEvent?e)?{
if(e.getSource()==jb){
try?{
pw.println(this.jtf.getText());
jta.append("客戶端對(duì)服務(wù)器說(shuō):???"+jtf.getText()+"\r\n");
jtf.setText("");
}?catch?(Exception?e1)?{
//?TODO?Auto-generated?catch?block
e1.printStackTrace();
}
}
}
public?void?keyTyped(KeyEvent?e)?{}
public?void?keyPressed(KeyEvent?e)?{
if(e.getKeyCode()==KeyEvent.VK_ENTER){
try?{
pw.println(this.jtf.getText());
jta.append("客戶端對(duì)服務(wù)器說(shuō):???"+jtf.getText()+"\r\n");
jtf.setText("");
}?catch?(Exception?e1)?{
//?TODO?Auto-generated?catch?block
e1.printStackTrace();
}
}
}
public?void?keyReleased(KeyEvent?e)?{}
}
網(wǎng)頁(yè)名稱:java簡(jiǎn)單通訊代碼,Java通信
瀏覽地址:http://sd-ha.com/article2/hdheoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)、、搜索引擎優(yōu)化、App設(shè)計(jì)、網(wǎng)站制作、動(dòng)態(tài)網(wǎng)站
聲明:本網(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)