日期:2014-05-18  浏览次数:20688 次

请教socket编程的问题
我是菜鸟,刚学socket编程,写了以下代码,想把客户机的asdf   asd字符传给服务端,不知道怎么不能实现.所以请教一下.  
服务器  
import   java.io.*;  
import   java.net.*;  
import   java.io.ObjectInputStream;  
import   java.io.ObjectOutputStream;  
public   class   Server1   {  
public   static   void   main(String[]   args)   throws   IOException{  
ServerSocket   server=new   ServerSocket(5678);  

Socket   client=server.accept();  
ObjectInputStream   in=new   ObjectInputStream(client.getInputStream());  
ObjectOutputStream   out=new   ObjectOutputStream(client.getOutputStream());  

try  
{  
String   a=(String)in.readObject();  
System.out.println(a);}  
catch(ClassNotFoundException   cnf)  
{cnf.printStackTrace();}  
}  
}  

客户机  
import   java.net.*;  
import   java.io.*;  
import   java.io.ObjectInputStream;  
import   java.io.ObjectOutputStream;  
public   class   Client1  
{  

public   static   void   main(String[]   args)throws   Exception  
{Socket   server;  
server=new   Socket( "127.0.0.1 ",5678);  
ObjectInputStream   in   =   new   ObjectInputStream(server.getInputStream());  
ObjectOutputStream   out   =   new   ObjectOutputStream(server.getOutputStream());  
out.writeObject( "asdf   asd ");  
out.flush();  

}  
}  


------解决方案--------------------

客户

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Other extends Frame{
Socket s1=null;
DataOutputStream dos= null;
TextField tfTxt = new TextField();
TextArea taConnect = new TextArea();

public static void main(String[] args) {

new Other().lanuchFrame();

}
public void lanuchFrame(){
setLocation(300,400);
this.setSize(300,300);
add(tfTxt,BorderLayout.SOUTH);
add(taConnect,BorderLayout.NORTH);
pack();

this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e ){
disConnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();

}
public void disConnect(){
try {
dos.close();
s1.close();
} catch (IOException e) {

e.printStackTrace();
}

}
public void connect()
{
try {
s1= new Socket( "127.0.0.1 ",8888);
dos= new DataOutputStream(s1.getOutputStream());
System.out.println( "connect! ");
} catch (UnknownHostException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}
private class TFListener implements ActionListener{
public void actionPerformed(ActionEvent e){
String str= tfTxt.