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();
}
}