小小示例,用于java与C#的TCP通信,java作为client,C#作为Server,Server用线程池。
主要功能为,client可以发送数据到Server,然后Server发送数据到client,断开;
相当于client发出请求,Server给予回应。
JAVA Client:
package com.cn.test;
import java.net.*;
import java.io.*;
public class TCPClient2 {
public static void main(String[] args) throws Exception {
TCPClient();
}
public static void TCPClient(){
String s="";
Socket mysocket;
InputStreamReader in=null;
OutputStreamWriter out=null;
try{
mysocket=new Socket("127.0.0.1",8002);
in = new InputStreamReader(mysocket.getInputStream(),"UTF8");
out = new OutputStreamWriter(mysocket.getOutputStream());
//从控制台输入数据
String sendMsg = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your value:");
sendMsg = br.readLine();
out.write(sendMsg); //通过 out向服务器写入信息。
out.flush();
int c =0;
while((c = in.read())>-1){
// System.out.print((char)c);//通过使用in读取服务器写入输出流的信息。堵塞状态,
s += (char)c;
}
//除非读取到信息。
System.out.println("客户收到服务器数据---->"+s);
in.close();
out.close();
mysocket.close();
}
catch(IOException e)
{
System.out.println(e.toString());
}
}
}
C# Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace TCPServer
{
class Program
{
static private System.Net.IPAddress MyIP = System.Net.IPAddress.Parse("127.0.0.1");
static private TcpListener listener = new TcpListener(MyIP, 8002);
static private String msg;
static void Main(string[] args)
{
ThreadPool.SetMaxThreads(10, 5);
ThreadPool.SetMinThreads(5, 5);
listener.Start();
//接收数据
while (true)
{
//测试是否有数据
try
{
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(callbackPoc, client);
}
catch (Exception re)
{
Console.WriteLine(re.Message);
}
}
listener.Stop();
}
//线程池回调函数
static void callbackPoc(Object k)
{
TcpClient client = (TcpClient)k;
NetworkStream ns = client.GetStream();
//StreamReader sr = new StreamReader(ns);//流读写器
//字组处理
while (true)
{
try
{
byte[] bytes = new byte[1024];
int bytesread = ns.Read(bytes, 0, bytes.Length);
msg = Encoding.Default.GetString(bytes, 0, bytesread);
//显示
//MessageBox.Show(msg);
Console.WriteLine(msg);
//将收到的数据回传给客户端,实际中,应该经过解析,将相应的数据回传给客户端。
NetworkStream sendStream = client.GetStream();
String msga = Console.ReadLine();
Byte[] sendBytes = Encoding.Default.GetBytes(msga);
sendStream.Write(sendBytes, 0, sendBytes.Length);
sendStream.Flush();
ns.Flush();
ns.Close();
sendStream.Close();
}
catch (Exception ex)
{
client.Close();
Console.WriteLine(ex.Message);
break;
}
}
}
}
}
另外,有四个C#方面TCPServer例子程序可供学习研究,下载地址
http://download.csdn.net/source/3232338