TCP发送接收信息
package Test_13;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientDemo {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket(InetAddress.getLocalHost(),9999);
OutputStream os = s.getOutputStream();
String str = "how are you";
os.write(str.getBytes());
s.close();
}
}
----------
package Test_13;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(9999);
Socket sk = ss.accept();
InputStream is = sk.getInputStream();
byte[] bys = new byte[1024];
int len;
while((len = is.read(bys)) != -1){
System.out.println(new String(bys,0,len));
}
InetAddress address = sk.getInetAddress();
System.out.println("sender-->"+address.getHostName());
sk.close();
}
}