socket编程到底是什么

socket编程到底是什么,第1张

socket 其实就是 *** 作系统提供给程序员 *** 作「网络协议栈」的接口,说人话就是,你能通过socket 的接口,来控制协议找工作,从而实现网络通信,达到跨主机通信。

协议栈的上半部分有两块,分别是负责收发数据的 TCP 和 UDP 协议,它们两会接受应用层的委托执行收发数据的 *** 作。

协议栈的下面一半是用 IP 协议控制网络包收发 *** 作,在互联网上传数据时,数据会被切分成一块块的网络包,而将网络包发送给对方的 *** 作就是由 IP 负责的。这里需要注意的是,服务端调用 accept 时,连接成功了会返回一个已完成连接的 socket,后续用来传输数据。

所以,监听的 socket 和真正用来传送数据的 socket,是「两个」 socket,一个叫作监听 socket,一个叫作已完成连接 socket。成功连接建立之后,双方开始通过 read 和 write 函数来读写数据,就像往一个文件流里面写东西一样。

java编程对于Socket之间的通信过程如下:

服务端往Socket的输出流里面写东西,客户端就可以通过Socket的输入流读取对应的内容。Socket与Socket之间是双向连通的,所以客户端也可以往对应的Socket输出流里面写东西,然后服务端对应的Socket的输入流就可以读出对应的内容。下面来看一些服务端与客户端通信的例子:

public class Server {

 

   public static void main(String args[]) throws IOException {

      //为了简单起见,所有的异常信息都往外抛

      int port = 8899;

      //定义一个ServerSocket监听在端口8899上

      ServerSocket server = new ServerSocket(port);

      //server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的

      Socket socket = serveraccept();

      //跟客户端建立好连接之后,我们就可以获取socket的InputStream,并从中读取客户端发过来的信息了。

      Reader reader = new InputStreamReader(socketgetInputStream());

      char chars[] = new char[64];

      int len;

      StringBuilder sb = new StringBuilder();

      while ((len=readerread(chars)) != -1) {

         sbappend(new String(chars, 0, len));

      }

      Systemoutprintln("from client: " + sb);

      readerclose();

      socketclose();

      serverclose();

   }

   

}客户端代码

Java代码  public class Client {  

   

   public static void main(String args[]) throws Exception {  

      //为了简单起见,所有的异常都直接往外抛  

      String host = "127001";  //要连接的服务端IP地址  

      int port = 8899;   //要连接的服务端对应的监听端口  

      //与服务端建立连接  

      Socket client = new Socket(host, port);  

      //建立连接后就可以往服务端写数据了  

      Writer writer = new OutputStreamWriter(clientgetOutputStream());  

      writerwrite("Hello Server");  

      writerflush();//写完后要记得flush  

      writerclose();  

      clientclose();  

   }  

     

}

这是我写过的一个简单聊天软件客户端  你参考下

import javautil;

import javaio;

import javanet;

import javaawt;

import javaxswing;

import javaawtevent;

public class testChatClient extends JFrame

{

private JTextArea jta = new JTextArea();

private JTextField jtf = new JTextField();

private JComboBox<String> jcb = new JComboBox<String>();

private JButton jbsend = new JButton("send");

private JButton jbrefresh = new JButton("refresh");

private InputStream input;

private OutputStream output;

private Socket socket;

public static String SERVER_IP = "1921681101";

public static int SERVER_PORT = 8888;

// Message 1 -> refresh message

// Message 2 -> send message

public testChatClient()

{

initComponents();

try

{

socket = new Socket(SERVER_IP,SERVER_PORT);

input = socketgetInputStream();

output = socketgetOutputStream();

}

catch(IOException e)

{

Systemerrprintln(e);

}

jbrefreshaddActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

jtasetText("");

try

{

if(socket == null)

socket = new Socket(SERVER_IP,SERVER_PORT);

outputwrite(0x31);

catch (IOException ex)

{

JOptionPaneshowConfirmDialog(null, ex);

}

}

});

jbsendaddActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

if(jtfgetText() == null || jtfgetText()equals(""))

return;

if(jtfgetText()length() >= 400)

{

JOptionPaneshowConfirmDialog(null,"最大字数不能超过400");

return;

}

try

{

String destination = jcbgetSelectedItem()toString();

String message = jtfgetText();

if(socket == null)

socket = new Socket(SERVER_IP,SERVER_PORT);

byte[] temp = new byte[3 + destinationgetBytes()length + messagegetBytes()length];

temp[0] = 0x32;

temp[1] = (byte)destinationgetBytes()length;

int i = 2;

for(int j = 0; j < destinationgetBytes()length ; i++ , j++)

temp[i] = destinationgetBytes()[j];

temp[i++] = (byte)messagegetBytes()length;

for(int j = 0 ; j < messagegetBytes()length ; i++ , j++)

{

temp[i] = messagegetBytes()[j];

Systemoutprintln();

}

outputwrite(temp);

jtaappend("me:\n");

jtaappend(jtfgetText());

jtaappend("\n");

jtfsetText("");

}

catch(IOException ex)

{

Systemerrprintln(ex);

}

}

});

try

{

jbrefreshdoClick();

while(true)

{

byte[] tempBytes = new byte[1000];

inputread(tempBytes);

int command = tempBytes[0] - 0x30;

// int readLength = inputread();

switch(command)

{

case 1:

{

int readLength = tempBytes[1];

String[] temp = new String(tempBytes,2,readLength,"UTF-8")split(";");

jcbremoveAllItems();

if(templength == 0 && temp[0]equals(""))

return;

for(int i = 0 ; i < templength ;i++)

{

jcbaddItem(temp[i]);

}

jcbsetSelectedIndex(0);

break;

}

case 2:

{

int readLength1 = tempBytes[1];

jtaappend(new String(tempBytes,2,readLength1,"UTF-8") + "\n");

int readLength2 = tempBytes[2 + readLength1];

jtaappend(new String(tempBytes,3 + readLength1,readLength2,"UTF-8") + "\n");

break;

}

}

}

}

catch(IOException e)

{

Systemerrprintln(e);

}

}

public static void main(String[] args) {

testChatClient frame = new testChatClient();

}

public void initComponents()

{

setLayout(new BorderLayout());

JPanel jpNorth = new JPanel();

jpNorthsetLayout(new BorderLayout());

jpNorthadd(jcb,BorderLayoutCENTER);

jpNorthadd(jbrefresh,BorderLayoutEAST);

JPanel jpSouth = new JPanel();

jpSouthsetLayout(new BorderLayout());

jpSouthadd(jtf,BorderLayoutCENTER);

jpSouthadd(jbsend,BorderLayoutEAST);

add(jpNorth,BorderLayoutNORTH);

add(jpSouth,BorderLayoutSOUTH);

add(new JScrollPane(jta),BorderLayoutCENTER);

thisgetRootPane()setDefaultButton(jbsend);

setDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

setSize(300,600);

setVisible(true);

}

}

以上就是关于socket编程到底是什么全部的内容,包括:socket编程到底是什么、java编程中,Socket通信是怎么实现的、java中如何创建socket连接的过程等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zz/9702635.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-01
下一篇 2023-05-01

发表评论

登录后才能评论

评论列表(0条)

保存