Java+利用UDP實現簡單雙機通信


計算機網絡實驗報告,給了很多課題,然后自己就對實現雙機通信比較感興趣,然后就希望做一個能夠實現雙機雙機通信的小聊天程序,本來還想用MFC做一個的,然后就在那扣了將近一天的MFC結果就自己做了一個最簡單的計算器程序,因為以前敲得代碼都是有關一些算法的,面向過程的,習慣了從主函數開始一點點讀代碼,然后用visual studio寫MFC程序突然沒有主函數讓我很不適應,不知道從哪開始寫代碼(當時寫那個cocos游戲也讓我納悶了一陣子),然后在百度主函數去哪了,最終也沒弄個所以然出來。只好對着最基礎的MFC入門寫了一個簡單的加法計算器,然后又加了一點自己的想法寫了一個能實現加減乘除的簡單計算器。然后限於時間關系和自己的能力只好放棄了。最后無意中發現了一個博主用Java寫了一個基於UDP的實現雙機通信的代碼,不過他的界面很簡單,所以我就借鑒了他的代碼的思想了解了Java的一點網絡編程的知識。自己做了一個簡單的Java版的基於UDP的雙機通信代碼。(本來想把參考的博主的網址給轉過來但寫的時候找不到了。。不好意思啊)經過了這次也讓我徹底明白了我不知道的知識還有很多很多啊。學然后知不足,教然后知困。小白寫的難免會有很多錯誤,歡迎指出錯誤。

代碼:

import java.text.SimpleDateFormat;
import java.util.*;
import java.io.File;
import java.io.IOException;
import java.math.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.naming.InitialContext;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.xml.stream.events.StartDocument;

import java.net.*;
class Window extends JFrame{
private JTextArea showArea ;
private JTextField inputField;
private String IPadress;
public void sentData(String Message){
byte[] dataarr = new byte[100010];
dataarr = Message.getBytes();
try{
InetAddress sentIP = InetAddress.getByName(IPadress);
DatagramSocket dsset = new DatagramSocket(62000);
DatagramPacket dprec = new DatagramPacket(dataarr, dataarr.length,sentIP, 64650);
//從己方62000端口發送到客戶端64650端口
dsset.send(dprec);
dsset.close();
}catch (UnknownHostException e){
e.printStackTrace();
}catch (SocketException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public void recieveData(){
byte[] dataarr = new byte[100010];
try{
DatagramSocket dsset = new DatagramSocket(63300);
//監聽己方63300端口收到的消息
DatagramPacket dprec = new DatagramPacket(dataarr, dataarr.length);
dsset.receive(dprec);
dsset.close();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
showArea.append(format.format(new Date())+"\n"+"新消息: "+new String(dataarr).trim()+"\n");
}catch (SocketException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public void startChat(){
JLabel displyjLabel = new JLabel("聊天窗口");
displyjLabel.setBounds(150, 10, 100, 15);
JPanel myJPanel = new JPanel();
myJPanel.setLayout(null);
this.setContentPane(myJPanel);
myJPanel.add(displyjLabel);
showArea = new JTextArea();
showArea.setLineWrap(true);
JScrollPane scrollpane=new JScrollPane(showArea);
scrollpane.setBounds(20,30,350,350);
scrollpane.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.CYAN, Color.BLUE, null, null));
scrollpane.setVisible(true);
inputField = new JTextField();
inputField.setBounds(20, 410, 280,25);
inputField.setVisible(true);
myJPanel.add(scrollpane);
JButton mybutton = new JButton("發送");
mybutton.setBounds(310,410,60,25);
myJPanel.add(mybutton);
myJPanel.add(inputField);
myJPanel.setVisible(true);
JButton quitjButton = new JButton("退出");
quitjButton.setBounds(250,450,100,30);
myJPanel.add(quitjButton);
quitjButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
JButton returnjButton = new JButton("返回主界面");
returnjButton.setBounds(20,450,100,30);
myJPanel.add(returnjButton);
returnjButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
initWindow();
}
});
this.setVisible(true);
inputField.requestFocus();
inputField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyChar()=='\n'){
String Message = inputField.getText().trim();
sentData(Message);
inputField.setText("");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

showArea.append(format.format(new Date())+"\n"+"我發送: "+Message+"\n");
}
}
});
mybutton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//當發送鍵被按下
String Message = inputField.getText().trim();
sentData(Message);
inputField.setText("");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
showArea.append(format.format(new Date())+"\n"+"我發送: "+Message+"\n");

}
});
}
public void initWindow(){
JPanel myjPanel = new JPanel();
myjPanel.setLayout(null);
this.setContentPane(myjPanel);
JLabel myjLabel = new JLabel("歡迎使用本聊天程序");
myjLabel.setBounds(50,100,300,40);
myjLabel.setForeground(Color.cyan);
myjLabel.setFont(new Font("HirakakuProN-W6", Font.BOLD, 30));
JLabel tishiJLabel = new JLabel("請輸入對方的IP地址:");
tishiJLabel.setBounds(15, 300, 150, 20);
final JTextField ipJTextField = new JTextField();
ipJTextField.setBounds(150, 300, 115, 20);
JButton okJButton = new JButton("確定");
okJButton.setBounds(280, 300, 70, 20);
ipJTextField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyChar()=='\n'){
startChat();
}
}
});
okJButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
IPadress = ipJTextField.getText();
startChat();
}
});
myjPanel.add(tishiJLabel);
myjPanel.add(myjLabel);
myjPanel.add(ipJTextField);
myjPanel.add(okJButton);
JButton quitjButton = new JButton("退出");
quitjButton.setBounds(150,350,100,30);
myjPanel.add(quitjButton);
quitjButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
this.setVisible(true);

}
public Window(){
this.setBounds(420, 100, 400, 550);
this.setLayout(null);
this.setTitle("聊天程序");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initWindow();
while(true){
recieveData();
}
}
}
public class server {
public static void main(String[] args) {
// TODO Auto-generated method stub
new Window();

}

}

客戶端的和上面的代碼基本一樣只不過設置一下端口號使其對應即可。

import java.text.SimpleDateFormat;
import java.util.*;
import java.io.File;
import java.io.IOException;
import java.math.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.naming.InitialContext;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.xml.stream.events.StartDocument;

import java.net.*;
class Window extends JFrame{
private JTextArea showArea ;
private JTextField inputField;
private String IPadress;
public void sentData(String Message){
byte[] dataarr = new byte[100010];
dataarr = Message.getBytes();
try{
InetAddress sentIP = InetAddress.getByName(IPadress);
DatagramSocket dsset = new DatagramSocket(60010);
DatagramPacket dprec = new DatagramPacket(dataarr, dataarr.length,sentIP, 63300);
//從己方60010端口發送到對方63300端口
dsset.send(dprec);
dsset.close();
}catch (UnknownHostException e){
e.printStackTrace();
}catch (SocketException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public void recieveData(){
byte[] dataarr = new byte[100010];
try{
DatagramSocket dsset = new DatagramSocket(64650);
DatagramPacket dprec = new DatagramPacket(dataarr, dataarr.length);
dsset.receive(dprec);
dsset.close();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
showArea.append(format.format(new Date())+"\n"+"新消息: "+new String(dataarr).trim()+"\n");
}catch (SocketException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public void startChat(){
JLabel displyjLabel = new JLabel("聊天窗口");
displyjLabel.setBounds(150, 10, 100, 15);
JPanel myJPanel = new JPanel();
myJPanel.setLayout(null);
this.setContentPane(myJPanel);
myJPanel.add(displyjLabel);
showArea = new JTextArea();
showArea.setLineWrap(true);
JScrollPane scrollpane=new JScrollPane(showArea);
scrollpane.setBounds(20,30,350,350);
scrollpane.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.CYAN, Color.BLUE, null, null));
scrollpane.setVisible(true);
inputField = new JTextField();
inputField.setBounds(20, 410, 280,25);
inputField.setVisible(true);
myJPanel.add(scrollpane);
JButton mybutton = new JButton("發送");
mybutton.setBounds(310,410,60,25);
myJPanel.add(mybutton);
myJPanel.add(inputField);
myJPanel.setVisible(true);
JButton quitjButton = new JButton("退出");
quitjButton.setBounds(250,450,100,30);
myJPanel.add(quitjButton);
quitjButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
JButton returnjButton = new JButton("返回主界面");
returnjButton.setBounds(20,450,100,30);
myJPanel.add(returnjButton);
returnjButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
initWindow();
}
});
this.setVisible(true);
inputField.requestFocus();
inputField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyChar()=='\n'){
String Message = inputField.getText().trim();
sentData(Message);
inputField.setText("");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
showArea.append(format.format(new Date())+"\n"+"我發送: "+Message+"\n");
}
}
});
mybutton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//當發送鍵被按下
String Message = inputField.getText().trim();
sentData(Message);
inputField.setText("");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
showArea.append(format.format(new Date())+"\n"+"我發送: "+Message+"\n");

}
});
}
public void initWindow(){
JPanel myjPanel = new JPanel();
myjPanel.setLayout(null);
this.setContentPane(myjPanel);
JLabel myjLabel = new JLabel("歡迎使用本聊天程序");
myjLabel.setBounds(50,100,300,40);
myjLabel.setForeground(Color.cyan);
myjLabel.setFont(new Font("HirakakuProN-W6", Font.BOLD, 30));
JLabel tishiJLabel = new JLabel("請輸入對方的IP地址:");
tishiJLabel.setBounds(15, 300, 150, 20);
final JTextField ipJTextField = new JTextField();
ipJTextField.setBounds(150, 300, 115, 20);
JButton okJButton = new JButton("確定");
okJButton.setBounds(280, 300, 70, 20);
ipJTextField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyChar()=='\n'){
startChat();
}
}
});
okJButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
IPadress = ipJTextField.getText();
startChat();
}
});
myjPanel.add(tishiJLabel);
myjPanel.add(myjLabel);
myjPanel.add(ipJTextField);
myjPanel.add(okJButton);
JButton quitjButton = new JButton("退出");
quitjButton.setBounds(150,350,100,30);
myjPanel.add(quitjButton);
quitjButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
this.setVisible(true);

}
public Window(){
this.setBounds(420, 100, 400, 550);
this.setLayout(null);
this.setTitle("聊天程序");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initWindow();
while(true){
recieveData();
}
}
}
public class client {
public static void main(String[] args) {
// TODO Auto-generated method stub
new Window();

}

}



注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: