1. java中的Socket API 对tcp,udp做了封装能够连接对方主机,收发数据
2. 服务器端 ServerSocket
a.可以与客户端建立连接,端口号一般使用4 位以上的数字
b.accept()方法:等待客户端连接的方法,如果没有连接,则一直等待
代码展示:
public class Server {
public static void main (String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5555 );
System.out .println("等待客户端连接" );
Socket accept = ss.accept();
InputStream is = accept.getInputStream();
byte [] bytes = new byte [1024 ];
while (true ) {
int read = is .read(bytes);
if (read == -1 ) {
break ;
}
String string = new String(bytes, 0 , read);
System.out .println(string );
}
accept.close();
}
}
3. 客户端 socket
a.客户端的对象有两个参数,第一个参数是服务器端的Ip地址,第二个参数是
端口号(必须与服务器端的端口号一致)
代码展示:
public class Demo {
public static void main (String[] args) throws IOException {
Socket sk = new Socket("localhost" , 5555 );
sk.getOutputStream().write("你好" .getBytes());
sk.close();
}
}
一.改进方案一
客户端:从键盘录入数据
代码展示:
public class Demo {
public static void main (String[] args) throws IOException {
Socket socket = new Socket("localhost" , 7777 );
Scanner sc = new Scanner(System.in );
while (true ) {
String s = sc.nextLine();
socket.getOutputStream().write(s.getBytes());
}
}
}
服务器端:把客户端传过来的数据显示到控制台上
代码展示:
public class Server {
public static void main (String[] args) throws IOException {
ServerSocket ss = new ServerSocket(7777 );
ExecutorService service = Executors.newCachedThreadPool();
System.out .println("等待客户端连接。。。" );
while (true ) {
Socket accept = ss.accept();
service.submit(() -> {
try {
byte [] bytes = new byte [1024 ];
InputStream inputStream = accept.getInputStream();
while (true ) {
int read = inputStream.read(bytes);
if (read == -1 ) {
break ;
}
String s = new String(bytes, 0 , read);
System.out .println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
}