1.写网络编程时,需要先运行服务器端,再运行客户端
2.InputStream和OutputStream是抽象类,无法实例化。需要使用Socket的getOutputStream()
getInputStream()
来返回输出流和输入流
3.ServerSocket 要接受Socket()连接,输出采用DataOutputStream的readUTF()来读
代码:
import java.net.;
import java.io.;
public class TCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6666);
try {
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
} catch(IOException e) {
e.printStackTrace();
}
}
}
import java.net.;
import java.io.;
public class TCPClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket(“127.0.0.1”,6666);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(“Hello Server!”);
dos.flush();
dos.close();
}
}