客户端程序
package test7;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
Socket sc = new Socket("127.0.0.1",7777);
OutputStream out = sc.getOutputStream();
out.write("who are you".getBytes());
InputStream in = sc.getInputStream();
byte[] b = new byte[20];
int num = in.read(b);
System.out.println(new String(b,0,num));
out.close();
in.close();
out.close();
sc.close();
}
}
服务器端程序
package test7;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
// 启动一个socket服务端(本质就是向操作系统注册一个端口号)
ServerSocket ss = new ServerSocket(7777);
System.out.println("服务端启动......,监听的端口为7777");
// (监听这个端口上的消息)
Socket sc = ss.accept(); // 等待并接收客户端的请求,建立socket连接; 这是一个阻塞方法
/**
* 从连接中接收数据
*/
// 从连接中接收数据,需要先获得一个输入流工具
InputStream in = sc.getInputStream();
// 从输入流中拿数据
/*int read = 0;
while((read = in.read())!=-1) {
System.out.println((char)read);
}*/
byte[] b = new byte[1024];
int num = in.read(b);
String string = new String(b,0,num);
System.out.println("收到客户端的消息:" + string);
/**
* 发送数据
*/
OutputStream out = sc.getOutputStream();
out.write("我是红红wwwww".getBytes());
out.close();
in.close();
sc.close();
}
}