网络编程用Socket实现聊天小程序

Posted 周娟娟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了网络编程用Socket实现聊天小程序相关的知识,希望对你有一定的参考价值。

客户端:

 

 1 package day18_网络编程;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.io.OutputStream;
 7 import java.net.Inet4Address;
 8 import java.net.InetAddress;
 9 import java.net.Socket;
10 import java.net.UnknownHostException;
11 import java.util.Scanner;
12 
13 public class Client {
14 
15     public static void main(String[] args) throws IOException {
16         InetAddress address = InetAddress.getByName("127.0.0.1");
17         while (true) {
18             Socket socket = new Socket(address, 8833);
19             // 向服务器传输数据
20             OutputStream os = socket.getOutputStream();
21             Scanner sc = new Scanner(System.in);
22             String word = sc.next();
23             os.write(word.getBytes());
24             socket.shutdownOutput();
25             
26             // 读取服务器发送过来的信息
27             InputStream is = socket.getInputStream();
28             byte[] bs = new byte[1024];
29             int length = -1;
30             while ((length = is.read(bs)) != -1) {
31                 String str = new String(bs, 0, length);
32                 System.out.println(str);
33             }
34             socket.shutdownInput();
35 
36             os.close();
37             is.close();
38         }
39     }
40 
41 }

 

 

服务器端:

 1 package day18_网络编程;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 import java.net.ServerSocket;
 7 import java.net.Socket;
 8 import java.util.Scanner;
 9 
10 import sun.nio.cs.ext.ISCII91;
11 
12 public class Server {
13 
14     public static void main(String[] args) throws IOException {
15         ServerSocket serverSocket = new ServerSocket(8833);
16         
17         while (true) {
18             Socket socket = serverSocket.accept();
19             // 读取客户端发送过来的信息
20             InputStream is = socket.getInputStream();
21             int length = -1;
22             byte[] bs = new byte[1024];
23             while ((length = is.read(bs)) != -1) {
24                 String msg = new String(bs, 0, length);
25                 System.out.println(msg);
26             }
27             socket.shutdownInput();
28             
29             // 向客户端发送信息
30             OutputStream os = socket.getOutputStream();
31             Scanner scanner = new Scanner(System.in);
32             String toWord = scanner.next();
33             os.write(toWord.getBytes());
34             socket.shutdownOutput();
35             is.close();
36             os.close();
37         }
38         
39     }
40 
41 }

 

以上是关于网络编程用Socket实现聊天小程序的主要内容,如果未能解决你的问题,请参考以下文章

C++语言实现网络聊天程序的设计与实现(基于TCP/IP协议的SOCKET编程)超详细(代码+解析)

Python实现群聊天小程序代码

前端小Demo:使用Socket实现简易网络聊天室

前端小Demo:使用Socket实现简易网络聊天室

C语言实现一个hello/hi的简单聊天程序并跟踪分析到系统调用

利用java的Socket实现一个简单hello/hi聊天程序