java 에서 UDP 간단 한 채 팅 프로그램 인 스 턴 스 코드
자바 에는 TCP 기반 네트워크 소켓 통신 도 있 고 UDP 기반 사용자 데이터 통신 도 있 습 니 다.UDP 의 정보 전송 속도 가 빠 르 지만 믿 을 수 없습니다!
UDP 통신 기반 기본 모드:
(1)데 이 터 를 패키지 라 고 부 르 고(예 를 들 어 편 지 를 봉투 에 넣 는 것 과 같다)데 이 터 를 목적지 로 보 냅 니 다.
(2)다른 사람 이 보 낸 패 킷 을 받 아들 이 고 패 킷 의 내용 을 살 펴 본다.
클 라 이언 트
package com.client.view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ObjectOutputStream;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.tools.ClientToServerThread;
/**
* @author lenovo
*
*/
public class JChatFrm extends JFrame implements ActionListener{
JTextArea jta;
JTextField jtf;
JButton jb;
JPanel jp;
String ownerId;
String friendId;
ClientToServerThread ctsT;
public static void main(String[] args) {
// TODO Auto-generated method stub
new JChatFrm();
}
public JChatFrm()
{
setTitle(" ");
jta=new JTextArea();
jtf=new JTextField(15);
jb=new JButton(" ");
jb.addActionListener(this);
jp=new JPanel();
jp.add(jtf);
jp.add(jb);
this.add(jta,"Center");
this.add(jp,"South");
// this.setTitle(ownerId+" "+friend+" ");
this.setIconImage((new ImageIcon("image/qq.gif").getImage()));
// this.setSize(300, 200);
this.setBounds(300, 200, 300, 200);
this.setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
ctsT = new ClientToServerThread(jta);
ctsT.start();
/** */
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
if(JOptionPane.showConfirmDialog(null, "<html><font size=3> ?</html>"," ",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE)==0)
{
System.exit(0);
ctsT.closeSocket();
}
else
{
return;
}
}
}
);
}
// ,
public void showMessage(String message)
{
String info= message;
this.jta.append(info);
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource()==jb)
{
byte buffer[] = jtf.getText().trim().getBytes();
ctsT.sendData(buffer);
}
}
}
package com.tools;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Properties;
import javax.swing.JTextArea;
import com.common.User;
/**
* @author lenovo
*
*/
public class ClientToServerThread extends Thread{
private String serverIP = "127.0.0.1";
private int serverPORT = 8888;
private int receivePORT = 6666;
//
private DatagramSocket sendSocket = null;
//
private DatagramPacket sendPacket = null;
//
private DatagramSocket receiveSocket = null;
//
private DatagramPacket receivePacket = null;
//
private int myPort = 0;
// IP
private String friendIP = null;
private int friendPort = 0;
//
public static final int BUFFER_SIZE = 5120;
private byte inBuf[] = null; //
private byte outBuf[] = null; //
JTextArea jta;
//
public ClientToServerThread(JTextArea jta) {
this.jta = jta;
getPropertiesInfo();
}
public void run() {
String receiveInfo = "";
try{
inBuf = new byte[BUFFER_SIZE];
receivePacket = new DatagramPacket(inBuf,inBuf.length);
receiveSocket = new DatagramSocket(receivePORT);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
while (true) {
if(receiveSocket == null){
break;
} else {
try {
receiveSocket.receive(receivePacket);
String message = new String(receivePacket.getData(),0,receivePacket.getLength());
jta.append(" "+message+"
");
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
}
/**
* IP、PORT
*/
private void getPropertiesInfo(){
Properties prop = new Properties();
InputStream inStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("ServerInfo.properties");
try{
//
prop.load(inStream);
}catch(IOException e){
e.printStackTrace();
}
//
serverIP = prop.getProperty("serverip");
serverPORT = Integer.parseInt(prop.getProperty("serverudp.port"));
receivePORT = Integer.parseInt(prop.getProperty("receiveudp.port"));
}
public void sendData(byte buffer[]){
try{
InetAddress address = InetAddress.getByName(serverIP);
// outBuf = new byte[BUFFER_SIZE];
sendPacket = new DatagramPacket(buffer,buffer.length,address,serverPORT);
sendSocket = new DatagramSocket();
sendSocket.send(sendPacket);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
public void closeSocket(){
receiveSocket.close();
}
}
서버:
package com.server.view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ObjectOutputStream;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.tools.ClientToServerThread;
/**
* @author lenovo
*
*/
public class JChatFrm extends JFrame implements ActionListener{
JTextArea jta;
JTextField jtf;
JButton jb;
JPanel jp;
String ownerId;
String friendId;
ClientToServerThread ctsT;
public static void main(String[] args) {
// TODO Auto-generated method stub
new JChatFrm();
}
public JChatFrm()
{
setTitle(" ");
jta=new JTextArea();
jtf=new JTextField(15);
jb=new JButton(" ");
jb.addActionListener(this);
jp=new JPanel();
jp.add(jtf);
jp.add(jb);
this.add(jta,"Center");
this.add(jp,"South");
// this.setTitle(ownerId+" "+friend+" ");
this.setIconImage((new ImageIcon("image/qq.gif").getImage()));
// this.setSize(300, 200);
this.setBounds(300, 200, 300, 200);
this.setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
ctsT = new ClientToServerThread(jta);
ctsT.start();
/** */
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
if(JOptionPane.showConfirmDialog(null, "<html><font size=3> ?</html>"," ",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE)==0)
{
System.exit(0);
ctsT.closeSocket();
}
else
{
return;
}
}
}
);
}
// ,
public void showMessage(String message)
{
String info= message;
this.jta.append(info);
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource()==jb)
{
byte buffer[] = jtf.getText().trim().getBytes();
ctsT.sendData(buffer);
}
}
}
package com.tools;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Properties;
import javax.swing.JTextArea;
import com.common.User;
/**
* @author lenovo
*
*/
public class ClientToServerThread extends Thread{
private String sendIP = "127.0.0.1";
private int sendPORT = 6666;
private int receivePORT = 8888;
//
private DatagramSocket sendSocket = null;
//
private DatagramPacket sendPacket = null;
//
private DatagramSocket receiveSocket = null;
//
private DatagramPacket receivePacket = null;
//
private int myPort = 0;
// IP
private String friendIP = null;
private int friendPort = 0;
//
public static final int BUFFER_SIZE = 5120;
private byte inBuf[] = null; //
private byte outBuf[] = null; //
JTextArea jta;
//
public ClientToServerThread(JTextArea jta) {
this.jta = jta;
getPropertiesInfo();
}
public void run() {
String receiveInfo = "";
try{
inBuf = new byte[BUFFER_SIZE];
receivePacket = new DatagramPacket(inBuf,inBuf.length);
receiveSocket = new DatagramSocket(receivePORT);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
while (true) {
if(receiveSocket == null){
break;
} else {
try {
receiveSocket.receive(receivePacket);
String message = new String(receivePacket.getData(),0,receivePacket.getLength());
jta.append(" "+message+"
");
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
}
/**
* IP、PORT
*/
private void getPropertiesInfo(){
Properties prop = new Properties();
InputStream inStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("ServerInfo.properties");
try{
//
prop.load(inStream);
}catch(IOException e){
e.printStackTrace();
}
//
receivePORT = Integer.parseInt(prop.getProperty("serverudp.port"));
}
public void sendData(byte buffer[]){
try{
InetAddress address = InetAddress.getByName(sendIP);
// outBuf = new byte[BUFFER_SIZE];
sendPacket = new DatagramPacket(buffer,buffer.length,address,sendPORT);
sendSocket = new DatagramSocket();
sendSocket.send(sendPacket);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
public void closeSocket(){
receiveSocket.close();
}
}
캡 처 실행:이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.