Java TcpUdp小例子非异步.docx
《Java TcpUdp小例子非异步.docx》由会员分享,可在线阅读,更多相关《Java TcpUdp小例子非异步.docx(21页珍藏版)》请在冰豆网上搜索。
![Java TcpUdp小例子非异步.docx](https://file1.bdocx.com/fileroot1/2022-12/14/daabbd01-eea2-40bb-9e7b-b269a443126b/daabbd01-eea2-40bb-9e7b-b269a443126b1.gif)
JavaTcpUdp小例子非异步
JavaTcpUdp小例子(非异步)(含源码)
TCP通信程序流程图:
UDP通信程序流程图:
运行结果
作为服务器端的电脑:
(IP:
192.168.1.102)
作为客户端的电脑:
(IP:
192.168.1.100)
源代码:
TCPServer.java
importjava.awt.BorderLayout;
importjava.awt.Button;
importjava.awt.Font;
importjava.awt.Frame;
importjava.awt.GridLayout;
importjava.awt.Panel;
importjava.awt.TextArea;
importjava.awt.TextField;
importjava.awt.event.MouseAdapter;
importjava.awt.event.MouseEvent;
importjava.awt.event.WindowAdapter;
importjava.awt.event.WindowEvent;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.IOException;
import.ServerSocket;
import.Socket;
publicclassTCPServerextendsFrame{
privateTextAreata=null;
privateTextFieldtf=null;
privatePanelsouthPanel=null;
privateButtonbtn=null;
privateThreadtReader=null;
privateSocketsConnect=null;
privatebooleankeepRunning=true;
TCPServermyFrame=null;
DataInputStreamdis=null;
DataOutputStreamdos=null;
/**
*主函数
*@paramargs
*/
publicstaticvoidmain(String[]args){
newTCPServer("TCPServerV1.0").launchServer(8887);
}
publicTCPServer(Stringtitle){
super(title);
setLocation(100,150);
ta=newTextArea();
add(ta,BorderLayout.CENTER);
southPanel=newPanel(newGridLayout(1,2));
tf=newTextField();
btn=newButton("Send");//"发送数据"
southPanel.add(tf);
southPanel.add(btn);
add(southPanel,BorderLayout.SOUTH);
pack();
myFrame=this;
btn.addMouseListener(newBtnMouseAdapter());
addWindowListener(newWindowAdapter(){
@Override
publicvoidwindowClosing(WindowEvente){
super.windowClosing(e);
keepRunning=false;
try{
if(tReader!
=null){
tReader.join(2000);
}
}catch(InterruptedExceptione1){
e1.printStackTrace();
}
myFrame.dispose();
System.exit(0);
}
});
setVisible(true);
}
publicvoidlaunchServer(intport){
ServerSocketss=null;
try{
ss=newServerSocket(port);
sConnect=ss.accept();
dos=newDataOutputStream(sConnect.getOutputStream());
dis=newDataInputStream(sConnect.getInputStream());
tReader=newThread(newSocketReader());
tReader.start();
ta.append("客户端"+sConnect.getInetAddress().toString()+"已经连接到此服务器。
\n");
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(ss!
=null){
ss.close();
ss=null;
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
privatevoidsendMsg(){
Stringtem=tf.getText();
if(tem!
=null&&dos!
=null){
try{
dos.writeUTF(tem);
ta.append("向"+sConnect.getInetAddress().toString()+":
"+sConnect.getPort()+"发送:
"+tem+"\n");
}catch(IOExceptione){
e.printStackTrace();
}
tf.setText("");
}
}
privateclassBtnMouseAdapterextendsMouseAdapter{
@Override
publicvoidmouseClicked(MouseEvente){
super.mouseClicked(e);
sendMsg();
}
}
privateclassSocketReaderimplementsRunnable{
publicvoidrun(){
StringstrRead=null;
while(keepRunning){
try{
strRead=dis.readUTF();
}catch(IOExceptione){
//e.printStackTrace();
System.out.println("连接已断开。
");
}
ta.append(sConnect.getInetAddress().toString()+":
"+sConnect.getPort()+"说:
"+strRead+"\n");
strRead=null;
}
}
}
}
TCPClient.java
importjava.awt.BorderLayout;
importjava.awt.Button;
importjava.awt.Frame;
importjava.awt.GridLayout;
importjava.awt.Panel;
importjava.awt.TextArea;
importjava.awt.TextField;
importjava.awt.event.MouseAdapter;
importjava.awt.event.MouseEvent;
importjava.awt.event.WindowAdapter;
importjava.awt.event.WindowEvent;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.IOException;
import.Socket;
import.UnknownHostException;
publicclassTCPClientextendsFrame{
privateTextAreata=null;
privateTextFieldtf=null;
privatePanelsouthPanel=null;
privateButtonbtn=null;
privateThreadtReader=null;
privateSocketsConnect=null;
privatebooleankeepRunning=true;
TCPClientmyFrame=null;
DataInputStreamdis=null;
DataOutputStreamdos=null;
/**
*主函数
*@paramargs
*/
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
newTCPClient("TcpClientV1.0").launchClient("192.168.1.102",8887);
}
publicTCPClient(Stringstring){
super(string);
setLocation(100,400);
ta=newTextArea();
add(ta,BorderLayout.CENTER);
southPanel=newPanel(newGridLayout(1,2));
tf=newTextField();
btn=newButton("Send");
southPanel.add(tf);
southPanel.add(btn);
add(southPanel,BorderLayout.SOUTH);
pack();
myFrame=this;
btn.addMouseListener(newBtnMouseAdapter());
addWindowListener(newWindowAdapter(){
@Override
publicvoidwindowClosing(WindowEvente){
super.windowClosing(e);
keepRunning=false;
try{
if(tReader!
=null){
tReader.join(2000);
}
}catch(InterruptedExceptione1){
e1.printStackTrace();
}
myFrame.dispose();
System.exit(0);
}
});
setVisible(true);
}
publicvoidlaunchClient(Stringip,intport){
try{
sConnect=newSocket(ip,port);
dos=newDataOutputStream(sConnect.getOutputStream());
dis=newDataInputStream(sConnect.getInputStream());
tReader=newThread(newSocketReader());
tReader.start();
ta.append("服务器端"+sConnect.getInetAddress().toString()+"已经连接。
\n");
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
privatevoidsendMsg(){
Stringtem=tf.getText();
if(tem!
=null&&dos!
=null){
try{
dos.writeUTF(tem);
ta.append("向"+sConnect.getInetAddress().toString()+":
"+sConnect.getPort()+"发送:
"+tem+"\n");
}catch(IOExceptione){
e.printStackTrace();
}
tf.setText("");
}
}
privateclassBtnMouseAdapterextendsMouseAdapter{
@Override
publicvoidmouseClicked(MouseEvente){
super.mouseClicked(e);
sendMsg();
}
}
privateclassSocketReaderimplementsRunnable{
publicvoidrun(){
StringstrRead=null;
while(keepRunning){
try{
strRead=dis.readUTF();
}catch(IOExceptione){
//e.printStackTrace();
System.out.println("连接已断开。
");
}
ta.append(sConnect.getInetAddress().toString()+":
"+sConnect.getPort()+"说:
"+strRead+"\n");
strRead=null;
}
}
}
}
UDPServer
importjava.awt.BorderLayout;
importjava.awt.Button;
importjava.awt.Frame;
importjava.awt.GridLayout;
importjava.awt.Panel;
importjava.awt.TextArea;
importjava.awt.TextField;
importjava.awt.event.MouseAdapter;
importjava.awt.event.MouseEvent;
importjava.awt.event.WindowAdapter;
importjava.awt.event.WindowEvent;
importjava.io.ByteArrayInputStream;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.IOException;
import.DatagramPacket;
import.DatagramSocket;
import.InetSocketAddress;
import.SocketException;
publicclassUDPServerextendsFrame{
privateTextAreata=null;
privateTextFieldtf=null;
privatePanelsouthPanel=null;
privateButtonbtn=null;
privateThreadtReader=null;
privateDatagramSocketsSender=null;
privateDatagramSocketsRecver=null;
privatebooleankeepRunning=true;
privateUDPServermyFrame=null;
privateDataInputStreamdis=null;
privateDataOutputStreamdos=null;
privateStringdestIp=null;
privateintportDest=0;
/**
*主函数
*@paramargs
*/
publicstaticvoidmain(String[]args){
newUDPServer("UDPServerV1.0").launchServer("192.168.1.100",6665,8888,6666);
}
publicvoidlaunchServer(StringdestIp,intportSend,intportDest,intportRecv){
this.destIp=destIp;
this.portDest=portDest;
try{
sSender=newDatagramSocket(portSend);//IP地址在数据包中标明
sRecver=newDatagramSocket(portRecv);
tReader=newThread(newUDPListener());
tReader.start();
}catch(SocketExceptione){
e.printStackTrace();
}
ta.append(String.format("启动服务器端(发送端口:
%d,接收端口:
%d)\n准备发送数据到:
%s:
%d\n\n",portSend,portRecv,destIp,portDest));
}
publicUDPServer(Stringtitle){
super(title);
setLocation(100,150);
ta=newTextArea();
add(ta,BorderLayout.CENTER);
southPanel=newPanel(newGridLayout(1,2));
tf=newTextField();
btn=newButton("Send");//"发送数据"
southPanel.add(tf);
southPanel.add(btn);
add(southPanel,BorderLayout.SOUTH);
pack();
myFrame=this;
btn.addMouseListener(newBtnMouseAdapter());
addWindowListener(newWindowAdapter(){
@Override
publicvoidwindowClosing(WindowEvente){
super.windowClosing(e);
sSender.close();
sRecver.close();
keepRunning=false;
try{
if(tReader!
=null){
tReader.join(2000);
}
}catch(InterruptedExceptione1){
e1.printStackTrace();
}
myFrame.dispose();
System.exit(0);
}
});
setVisible(true);
}
privateclassBtnMouseAdapterextendsMouseAdapter{
@Override
publicvoidmouseClicked(MouseEvente){
super.mouseClicked(e);
sendMsg();
}
}
privatevoidsendMsg(){
Stringtem=tf.getText();
byte[]bArray=tem.getBytes();
if(bArray!
=null&&sSender!
=null){
try{
DatagramPacketdp=newDatagramPacket(bArray,bArray.length,newInetSocketAddress(destIp,portDest));
sSender.send(dp);
ta.append("\n向"+dp.getAddress()+":
"+dp.getPort()+"发送:
"+tem+"\n");
}catch(IOExceptione){
e.print