日期:2014-05-20  浏览次数:20851 次

一个简单的Socket程序出问题了
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.io.*;
import java.net.*;
public class DataSocketSer 
{
public static void main(String[] args) 
{
String str="";
Frame f=new Frame();
f.setSize(355, 355);
f.setLayout(new FlowLayout(FlowLayout.LEFT,10,10));
Label l=new Label(" 111111111111 ");
f.add(l);
f.setVisible(true);
DatagramSocket da=null;
try
{
da=new DatagramSocket(4700);
}
catch(SocketException e)
{
e.getMessage();
}
byte b[]="wwwwwwwww".getBytes();
InetAddress address=null;
try
{
address=InetAddress.getByName("127.0.0.1");
}
catch(UnknownHostException e)
{
e.getMessage();
}
DatagramPacket dp =new DatagramPacket(b,6,address,4700);
try
{
da.send(dp);
}
catch( IOException e)
{
e.getMessage();
}
}
}



import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.io.*;
import java.net.*;
public class DataSocketSer 
{
public static void main(String[] args) 
{
String str="";
Frame f=new Frame();
f.setSize(355, 355);
f.setLayout(new FlowLayout(FlowLayout.LEFT,10,10));
Label l=new Label(" 111111111111 ");
f.add(l);
f.setVisible(true);
DatagramSocket da=null;
try
{
da=new DatagramSocket(4700);
}
catch(SocketException e)
{
e.getMessage();
}
byte b[]="wwwwwwwww".getBytes();
InetAddress address=null;
try
{
address=InetAddress.getByName("127.0.0.1");
}
catch(UnknownHostException e)
{
e.getMessage();
}
DatagramPacket dp =new DatagramPacket(b,6,address,4700);
try
{
da.send(dp);
}
catch( IOException e)
{
e.getMessage();
}
}
}

我先打开第一个程序,再打第二个程序,但是没什么反应,这是怎么一回事

------解决方案--------------------
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.*;
public class server extends JFrame implements Runnable,ActionListener{

JTextField out;
JTextArea text;
JPanel p1;
JButton btn;
JScrollPane textPanel;
Thread tr;
 InetAddress ip = null;

// 构造方法:
 
 public server(){
Container c = getContentPane();
out = new JTextField(15);
text = new JTextArea(30,30);
btn = new JButton("确定");
textPanel = new JScrollPane(text);
text.setEditable(false);
text.setLineWrap(true);
p1 = new JPanel();
p1.add(out);
p1.add(btn);
out.addActionListener(this);
btn.addActionListener(this);
c.add(textPanel,"Center");
c.add(p1,"South");
setSize(400,400);
setVisible(true);
tr = new Thread(this);
tr.start();
addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we){
System.exit(0);}
});
 }


 public void actionPerformed(ActionEvent ae){
 
 if((ae.getSource() == btn) || (ae.getSource() == out)){

byte buffer[] = (out.getText()).trim().getBytes();
try{

ip = InetAddress.getByName("127.0.0.1");
DatagramPacket da = new DatagramPacket(buffer,buffer.length,ip,2006);
DatagramSocket mail = new DatagramSocket();
text.append("输入:" + out.getText() + '\n');
mail.send(da);