本帖最后由 ZSMAN 于 2015-5-4 12:05 编辑
import java.io.*;
import java.net.*;
class TcpC {
private Socket s;
public TcpC() throws Exception {
s=new Socket("127.0.0.1",8888);//客户端要明确服务端的IP和监听端口
}
public String getIn() throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
return s;
}
public void run() throws Exception {
OutputStream out=s.getOutputStream();
InputStream in=s.getInputStream();
byte[] buf=new byte[1024];
while(true) {
String s=getIn();
out.write(s.getBytes());
if("over".equals(s)) break;
int len=in.read(buf);
System.out.println(new String(buf,0,len));
}
s.close();
}
}
class TcpS {
private Socket s;
private ServerSocket ss;
public TcpS() throws Exception {
ss=new ServerSocket(8888);//服务端要监听端口
}
public void run() throws Exception {
s=ss.accept();
OutputStream out=s.getOutputStream();
InputStream in=s.getInputStream();
byte[] buf=new byte[1024];
while(true) {
int len=in.read(buf);
String s=new String(buf,0,len);
if("over".equals(s)) break;
s=s.toUpperCase();
out.write(s.getBytes());
}
s.close();
}
}
public class net {
public static void main(String[] args) throws Exception {
TcpC a=new TcpC();
//TcpS a=new TcpS();
a.run();
}
}
|