public class temp extends Thread {
private Socket s;
public temp(Socket s) {
this.s = s;
}
// 以下为服务器端程序
public void run() {
try {
OutputStream os = s.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
bos.write("Server to client".getBytes());
bos.flush();
//向客户端发送数据流
InputStream is = s.getInputStream();
byte[] buf = new byte[1024];
int len = is.read(buf);
System.out.println(new String(buf, 0, len));
//从客户端读取数据流
bos.close();
is.close();
s.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void server() {
try {
ServerSocket ss = new ServerSocket(6060);
while (true) {
Socket s = ss.accept();
new temp(s).start();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
//以下为客户端程序
public static void client() {
try {
Socket s = new Socket(InetAddress.getByName(null), 6060);
OutputStream os = s.getOutputStream();
InputStream is = s.getInputStream();
byte[] buf = new byte[1024];
int len = is.read(buf);
System.out.println(new String(buf, 0, len));
os.write("client to server".getBytes());
os.close(); ;
is.close();
s.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 执行时含有参数 启动服务器 否则启动客户端
public static void main(String[] args) {
if (args.length > 0)
server();
else
client();
}