首页 > 代码库 > java网络基础------3------实现服务器

java网络基础------3------实现服务器

1、SeverSocket server = new SockeSever(8189);          //建立一个监听本机8189端口的服务器

2、Socket incoming = server.accept();                      //server.accept()是告诉服务器不停的等待,知道有socket接入,生成一个socket  s。

 

例子,服务器端代码:

             

 1 package com.socket;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 import java.io.PrintWriter;
 7 import java.net.ServerSocket;
 8 import java.net.Socket;
 9 import java.util.Scanner;
10 
11 public class Sever {
12     public static void main(String args[]) throws IOException{
13         try(ServerSocket server= new ServerSocket(8191)){
14             try(Socket incomming = server.accept()){
15                 InputStream in = incomming.getInputStream();
16                 OutputStream out = incomming.getOutputStream();
17                 try(Scanner sc = new Scanner(in)){
18                     PrintWriter writer = new PrintWriter(out,true);
19                     writer.println("enter exit,to exit");
20                     boolean t = false;
21                     while(!t && sc.hasNext()){
22                         String line = sc.nextLine();
23                         writer.println("Echo:"+line);
24                         if(line.trim().equals("exit"))
25                             t = true;
26                     }
27                 }
28             }
29         }
30     }
31 
32 }

 

java网络基础------3------实现服务器