举例说明Socket类与ServerSocket类的用途
2个回答
展开全部
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) throws Exception{
ServerSocket ss = new ServerSocket(6666);
while(true) {
Socket s = ss.accept();
System.out.println("A Client Connect!");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
dis.close();
s.close();
}
}
}
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);
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
Thread.sleep(30000);
dos.writeUTF("Hello Server!");
dos.flush();
dos.close();
s.close();
}
}
自己运行下就知道了 ,先运行TCPServer.java
import java.io.*;
public class TCPServer {
public static void main(String[] args) throws Exception{
ServerSocket ss = new ServerSocket(6666);
while(true) {
Socket s = ss.accept();
System.out.println("A Client Connect!");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
dis.close();
s.close();
}
}
}
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);
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
Thread.sleep(30000);
dos.writeUTF("Hello Server!");
dos.flush();
dos.close();
s.close();
}
}
自己运行下就知道了 ,先运行TCPServer.java
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询