TCPSeverSocket创建一个TCP服务器端
1.创立一个SSeverSocket专门与客户端相连
2,使用OuputStream读用户端发来的数据
3,用close 方法关闭
package TCPSeverSocket;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPSever {
public static void main(String[] args) throws Exception{
@SuppressWarnings("resource")
ServerSocket seversocket=new ServerSocket(7788);
while(true) {
Socket client=seversocket.accept();
System.out.println("与客户端连接成功,开始进行数据交互!");
OutputStream os=client.getOutputStream();
os.write(("服务器端向客户端做出响应!").getBytes());
Thread.sleep(5000);
os.close();
client.close();
}
}
}
TCPClient创立一个用户端
1.创立一个Socket专门与服务器
package TCPSeverSocket; import java.io.InputStream; import java.net.InetAddress; import java.net.Socket; public class TCPClient { public static void main(String[] args) throws Exception{ Socket client=new Socket(InetAddress.getLocalHost(),7788); InputStream is=client.getInputStream(); byte[] buf=new byte[1024]; int len=is.read(buf); while(len!=-1) { System.out.println(new String(buf,0,len)); len=is.read(buf); } is.close(); client.close(); } }
相连
2,使用InputStream写入数据发送给服务器端
3,用close 方法关闭