1、客户端
package cd.itcast.xieyi; import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException; /*
* tcp协议的socket
* socket(客户端),tcp的客户端一旦启动马上要与服务端建立连接。
* ServerSocket(服务端类)
*
* tcp客户端的使用步骤:
*/
public class Demo2Client {
public static void main(String[] args) throws UnknownHostException, IOException {
//建立tcp的客户端服务
Socket socket = new Socket(InetAddress.getLocalHost(), 9090);
//获得输出流对象
OutputStream outputStream = socket.getOutputStream();
//利用输出流写出数据
outputStream.write("甘兴瑞您好!!".getBytes());
//关闭资源
socket.close();
}
}
2、服务端
package cd.itcast.xieyi; import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket; public class Demo2Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9090);
//接受客户端连接,有等待特性,返回socket对象
Socket socket = serverSocket.accept();
//获得输入流
InputStream inputStream = socket.getInputStream();
//读入数据
byte[] buf = new byte[1024];
int length=0;
length = inputStream.read(buf);
System.out.println("服务端接受到的数据:"+new String(buf,0,length));
//关闭资源
socket.close();
}
}
3、
根据谁来的消息,根据socket,对应的返回信息。