发送方
server
package 网络编程;
import java.net.*;
import java.io.*;
public class Sever {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
new TCPSever().listen();
}
}
class TCPSever{
public void listen() throws Exception{
ServerSocket sever=new ServerSocket(8002);
Socket client =sever.accept();
OutputStream os=client.getOutputStream();
os.write(("Hello World!").getBytes());
Thread.sleep(5000);
os.close();
client.close();
}
}
接收方
client
package 网络编程;
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
new TCPClient().connect();
}
}
class TCPClient{
public void connect() throws Exception{
Socket client =new Socket(InetAddress.getLocalHost(),8002);
InputStream is=client.getInputStream();
byte[] buf=new byte[1024];
int len=is.read(buf);
System.out.println(new String(buf,0,len));
client.close();
}
}