日期:2014-05-20 浏览次数:21122 次
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
/**
*send string to each connected client
*/
public class MainClass4 extends Thread
{
Socket socket;
public void run()
{
try
{
String s="I am a server.";
PrintWriter pw=new PrintWriter(socket.getOutputStream(),true);
pw.println(s);
socket.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
/**
*main entry
*/
public static void main(String[] args)throws Exception
{
ServerSocket ssock=new ServerSocket(8080);
while(true)
{
Socket esock=null;
esock=ssock.accept();
System.out.println("Connected");
MainClass4 t=new MainClass4();
t.socket=esock;
t.start();
esock.close();
}
}
}
import java.io.*;
import java.net.*;
/**
*MainClass4 Client
*/
public class MainClass4Client
{
/**
*mian entry
*/
public static void main(String[]args)throws IOException
{
Socket sock=null;
BufferedReader bin=null;
try
{
sock=new Socket("localhost",8080);
bin=new BufferedReader(new InputStreamReader(sock.getInputStream()));
}
catch(UnknownHostException e)
{
System.err.println("Don't know about host localhost");
System.exit(1);
}
catch(IOException e)
{
System.err.println(e);
}
System.out.println(bin.readLine());
bin.close();
sock.close();
}
}