import java.net.*;
import java.io.*;
class Client
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("127.0.0.1",10004);
OutputStream os=s.getOutputStream();
os.write("服务端,你好".getBytes());
InputStream is=s.getInputStream();
byte[] buf=new byte[1024];
int len=0;//is.read(buf);
//System.out.print(new String(buf,0,len));
while((len=is.read(buf))!=-1)//像上面一样直接读就可以,加入while后,就收不到服务端的发来的消息,不明白为什么,如果要读的东西很多,应该要分几次读的
{
System.out.print(new String(buf,0,len));
}
s.close();
}
}
class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(10004);
Socket s=ss.accept();
System.out.println(s.getInetAddress().getHostAddress());
InputStream is=s.getInputStream();
byte[] buf=new byte[1024];
int len=0;//is.read(buf);
//System.out.print(new String(buf,0,len));
while((len=is.read(buf))!=-1)
{
System.out.print(new String(buf,0,len));
}
OutputStream os=s.getOutputStream();
os.write("客户端,你好".getBytes());//这句话客户端收不到
s.close();
ss.close();
}
}
|