我有两个用两个不同的Java文件编写的程序1.客户端代码2.服务器代码
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
class Destination extends JFrame
{
JLabel l1;
JTextArea ta;
Container cnt;
DatagramSocket ds;
Destination() throws Exception
{
l1 = new JLabel("Received Message :");
ta = new JTextArea(10, 25);
cnt = getContentPane();
cnt.setLayout(new FlowLayout());
cnt.add(l1);
cnt.add(ta);
setSize(400, 200);
setDefaultCloseOperation(2);
setVisible(true);
ds = new DatagramSocket(210);
}
void dispMsg() throws Exception
{
while (true)
{
byte b[] = new byte[50];
ds.receive(new DatagramPacket(b, 0, b.length));
String msg = new String(b, 0, b.length);
msg = msg.trim();
ta.append(msg + "\n");
if (msg.equals("bye"))
{
break;
}
}
}
public static void main(String ar[]) throws Exception
{
(new Destination()).dispMsg();
}
}
2.服务器端
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
class Source extends JFrame implements ActionListener
{
JLabel l1;
JTextField t1;
JButton btn;
Container cnt;
DatagramSocket ds;
Source() throws Exception
{
l1 = new JLabel("Enter Message");
t1 = new JTextField(20);
btn = new JButton("Send Message");
btn.addActionListener(this);
cnt = getContentPane();
cnt.setLayout(new FlowLayout());
cnt.add(l1);
cnt.add(t1);
cnt.add(btn);
setSize(400, 200);
setDefaultCloseOperation(2);
setVisible(true);
ds = new DatagramSocket(210);
}
public void actionPerformed(ActionEvent e)
{
try
{
ds.send(new DatagramPacket(t1.getText().getBytes(), 0, t1.getText().length(),
InetAddress.getLocalHost(), 211));
}
catch (Exception e1)
{
JOptionPane.showMessageDialog(this, e1, "Error", 0);
}
}
public static void main(String ar[]) throws Exception
{
new Source();
}
}
我想通过cmd运行这两个程序,我应该先运行哪个程序,当我运行第一个代码时,cmd被禁用,不允许我运行第二个代码,建议我如何运行两个程序
更新
服务器和客户端中的端口号不同。211,210选择一个!您的程序将运行,但是客户端将无法连接到服务器并接收消息。
ds = new DatagramSocket(210
);
ds.send(new DatagramPacket(t1.getText()。getBytes(),0,t1.getText()。length(),InetAddress.getLocalHost(),211
));
我应该先跑哪一个
服务器代码
我如何运行两个程序
使用2个不同的cmd
Steps:
输出和运行参考:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句