socket连接 java服务器端 C#客户端进行交互 简单例子

java服务器端代码:

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {

 private ServerSocket ss;
 private Socket socket;
 private BufferedReader in;
 private PrintWriter out;

 public SocketServer() {
  try {
   ss = new ServerSocket(80);

   while (true) {
    socket = ss.accept();
    in = new BufferedReader(new InputStreamReader(socket
      .getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);

    String line = in.readLine();
    out.println("you input is :" + line);
    System.out.println("server:"+line);
    out.close();
    in.close();
    socket.close();
    ss.close();
   }
  } catch (IOException e) {
  }
 }

 public static void main(String[] args) {
  new SocketServer();
 }

}

 

C#客户端代码:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace DreamCommunications
{
    class SocketClient
    {
        private String ip = "192.168.1.101";
        private int port = 80;
        private IPEndPoint iped ;

        public String login(String str) {
            String flag = "";
            Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
          
            socket.Connect(ip,port);

            String info = str+"/n/b";         //注意 因为java写的服务器端使用的是readLine()方法,这里在结束的时候必须增加/n换行符,否则程序将会停滞在java服务器端的readLine一行             byte[] b = System.Text.Encoding.UTF8.GetBytes(info);

            socket.Send(b);

            string strRec ="";
           
            byte[] rb = new byte[socket.ReceiveBufferSize];
           
            socket.Receive(rb);
            strRec  = System.Text.Encoding.UTF8.GetString(rb);
           
            flag = strRec;

            socket.Close();

 

            return strRec;
        }
    }
}

你可能感兴趣的:(java,dotnet,socket)