TCP/IP/Socket

本文介绍了Socket连接模型的基本原理,包括服务端与客户端的交互过程。服务端通过ServerSocket监听指定端口并接受客户端连接请求,客户端则主动发起连接请求到指定的服务端地址。文中提供了完整的Java实现代码示例,展示了如何进行数据的发送与接收。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

socket连接模型

服务端:ServeSocket(“端口”);

ServerSocket.accept();//阻塞

//等待客服端的请求

Socket//得到

OutputStream;

InputStream;

Socket.close;

客服端:Socket(“服务器Ip”,"端口");

OutputStream;

InputStream;

Socket.close;

测试代码:服务端:

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;

public class Serve {
/**
* @param args
*/
public static void main(String[] args) {
new Serve().start();
}

public void start(){
ServerSocket ss =null;//定义Serversocket
Socket s  =null;//定义Socket
PrintWriter writer=null;
int port=8888;
String str="[%s:%s]";
try {
//ServeSocket
ss = new ServerSocket(port);
System.out.println("服务器启动了。。");
while(true){
//阻塞
s = ss.accept();
//socket
//拿流
System.out.println("客服端连接上了");
System.out.println(String.format(str, s.getInetAddress().getHostAddress(),s.getPort()));
writer = new PrintWriter(s.getOutputStream());//拿到写入流
//writer.write("hello\r\n");
writer.println("hello");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(writer!=null)
writer.close();
if(s!=null)
s.close();
if(ss!=null)
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


}


客户端代码:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.logging.Logger;




public class Client {


/**
* @param args
*/
public static void main(String[] args) {
new Client().start();
}

public void start(){
Socket s = null;
BufferedReader br=null;
try{
s = new Socket("192.168.61.71", 8888);
System.out.println("客服端启动了");
br = new BufferedReader(new InputStreamReader(s.getInputStream()));

System.out.println(br.readLine());
}catch(Exception e){

} finally{
if(br!=null)
try {
br.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(s!=null)
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


}


最后还要注意的是PrintWriter的write方法和println方法

查阅api:/**
     * Terminates the current line by writing the line separator string.  The
     * line separator string is defined by the system property
     * <code>line.separator</code>, and is not necessarily a single newline
     * character (<code>'\n'</code>).
     */
    public void println() {
        newLine();
    }


/******************************/

 private void newLine() {
        try {
            synchronized (lock) {
                ensureOpen();
                out.write(lineSeparator);//================这里是一个区别
                if (autoFlush)
                    out.flush();//=======================这里是一个区别
            }
        }


 public PrintWriter(Writer out,
                       boolean autoFlush) {
        super(out);
        this.out = out;
        this.autoFlush = autoFlush;
        lineSeparator = java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("line.separator"));
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值