package network;
import java.io.IOException;
/**
* @function : 入口文件
* @author :jy
* @company :万里网
* @date :2011-6-29
*/
public class SocketMainTest {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
if(args.length > 0){
new ServerSocketP().run();
}else{
new ClientSocketP().send();
}
}
}
package network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* @function : 服务器端,当接收到客户端请求后,发送并接收数据,最后关闭连接与服务器。
* @author :jy
* @company :万里网
* @date :2011-6-29
*/
public class ServerSocketP {
public void run() throws IOException{
java.net.ServerSocket server = new java.net.ServerSocket(6000);
Socket client = server.accept();
OutputStream o = client.getOutputStream();
InputStream in = client.getInputStream();
o.write("hello, this server send".getBytes());
byte[] b = new byte[100];
int len = in.read(b);
System.out.println(new String(b, 0, len));
o.close();
in.close();
client.close();
server.close();
}
}
package network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/**
* @function : 客户端,请求服务器端后发送并接收数据,最后关闭与服务器连接。
* @author :jy
* @company :万里网
* @date :2011-6-29
*/
public class ClientSocketP {
public void send() throws IOException{
Socket client = new Socket(InetAddress.getByName("localhost"), 6000);
OutputStream out = client.getOutputStream();
InputStream in = client.getInputStream();
byte[] b = new byte[100];
int len = in.read(b);
System.out.println(new String(b, 0, len));
out.write("this is client".getBytes());
out.close();
in.close();
client.close();
}
}