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 联系我们: