这个我正好做过,把代码给出粘过来吧,记得把分给我. (后边有图片的)
服务器端程序:
using System
using System.Collections.Generic
using System.Linq
using System.Text
using System.Threading
using System.Net
using System.Net.Sockets
using System.Windows.Forms
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private static TcpListener listener
private static Socket clientsocket
private static IPEndPoint listenPort
private static Thread clientservice
delegate void setTextSring(string str)
public Form1()
{
InitializeComponent()
}
private void button1_Click(object sender, EventArgs e)
{
string port = textBox1.Text
if (port == "")
{
MessageBox.Show("搏哪请输入监听端哪液口")
return
}
try
{
if (Int32.Parse(port) > 0)
{
listenPort = new IPEndPoint(IPAddress.Any, Int32.Parse(port))
Thread thr = new Thread(new ThreadStart(StartListening))
thr.Start()
}
else
MessageBox.Show("监听端口号必须大于0,建议使用大于1024的端口")
}
catch (Exception ex)
{
MessageBox.Show(ex.Message)
}
}
private void StartListening()
{
listener = new TcpListener(listenPort)
SetText("IP: " + Convert.ToString(listenPort) + "\r\n")
listener.Start()
MessageBox.Show("服务已启动。。。")
while (true)
{
try
{
Socket s = listener.AcceptSocket()
clientsocket = s
clientservice = new Thread(new ThreadStart(ServiceClient))
clientservice.Start()
}
catch (Exception e)
{
MessageBox.Show(e.ToString())
}
}
}
private void SetText(string str)
{
if (textBox2.InvokeRequired)
{
setTextSring sts = new setTextSring(SetText)
Invoke(sts, new object[] { str })
}
else
{
this.textBox2.Text += str
}
}
public static string byteToHexStr(byte[] bytes)
{
string returnStr = ""
if (bytes != null)
{
for (int i = 0 i < bytes.Length i++)
{
returnStr += bytes[i].ToString("X2") + " "李银物
}
}
return returnStr
}
private void ServiceClient()
{
Socket client = clientsocket
bool keepalive = true
while (keepalive)
{
byte[] buffer = new Byte[60]
client.Receive(buffer)
string clientcommand = byteToHexStr(buffer)
clientcommand += "\r\n"
SetText(clientcommand)
}
}
private static void SendToClient(Socket cli, string str)
{
Byte[] sendbytes = System.Text.Encoding.UTF8.GetBytes(str.ToCharArray())
cli.Send(sendbytes)
}
}
}
客户端程序:
using System
using System.Collections.Generic
using System.ComponentModel
using System.Data
using System.Drawing
using System.Linq
using System.Text
using System.Windows.Forms
using System.Net
using System.Net.Sockets
using System.Threading
using System.IO
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent()
}
private TcpClient clientsocket
private NetworkStream ns
private StreamReader sr
private bool bConn = false
private string clientname = ""
private Thread t
private void button2_Click(object sender, EventArgs e)
{
string ip = textBox1.Text
int port = Int32.Parse(textBox2.Text)
if (port > 0)
{
if (!EstablishConnection(ip, port))
return
}
else
{
MessageBox.Show("duankouhaodayu0")
return
}
t = new Thread(new ThreadStart(recivechat))
t.Start()
MessageBox.Show("连接成功!")
}
private bool EstablishConnection(string IP, int port)
{
try
{
clientsocket = new TcpClient(IP, port)
ns = clientsocket.GetStream()
sr = new StreamReader(ns)
bConn = true
return true
}
catch (Exception e)
{
MessageBox.Show(e.ToString())
}
return false
}
private void recivechat()
{
bool keeplive = true
while (keeplive)
{
try
{
Byte[] buffer = new Byte[2048]
ns.Read(buffer, 0, buffer.Length)
string chatter = System.Text.Encoding.UTF8.GetString(buffer)
textBox4.Text += chatter
}
catch (Exception e)
{
MessageBox.Show(e.ToString())
}
}
}
private void button1_Click(object sender, EventArgs e)
{
string msg = textBox3.Text
Byte[] outbytes = System.Text.Encoding.UTF8.GetBytes(msg.ToCharArray())
ns.Write(outbytes, 0, outbytes.Length)
MessageBox.Show("发送成功!")
}
}
}
我把程序的界面图片给你,你参考下
服务器监听端口宽肢 做个无限循环 接到一个连纤巧悔接就创建一个通道线程,并将通道线程存储到一个list集合中import java.io.BufferedReaderimport java.io.IOExceptionimport java.io.InputStreamReaderimport java.io.PrintWriterimport java.net.ServerSocketimport java.net.Socketimport java.text.SimpleDateFormatimport java.util.ArrayListimport java.util.Dateimport java.util.List/* * 4.用socket通讯写出多个客户端和一个服务器端的通讯, * 要求客户发送数据后能够回显相同的数据(回显功能)(实用TCP方式)。 */public class Test4Server { // 主入口public static void main(String[] args) throws IOException {scoketServer() } // 开启的tcp8888监听端口public static void scoketServer() throws IOException {ServerSocket server = new ServerSocket(8888) while (true) {// 未连通前线程阻塞,连通后开启一个socket通道线程后继续监听8888端口Socket socket = server.accept() System.out.println(socket.getInetAddress().getHostAddress()+ "连接进毁正入") new SocketThread(socket).start() }} } // 一个服务器端口中监听多个客服端通道线程class SocketThread extends Thread {// 所有通道写入流的集合private static List<PrintWriter>list =new ArrayList<PrintWriter>()private BufferedReader bufferedReader private PrintWriter printWriterpublic SocketThread(Socket socket) throws IOException {this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())) this.printWriter = new PrintWriter(socket.getOutputStream()) list.add(printWriter) } @Overridepublic void run() {String string = null while (true) {try {// 服务器在通道中读到的信息回显给客服端string = bufferedReader.readLine() System.out.println("客服端信息:" + string) for(PrintWriter printWriter:list ){printWriter.write("服务器回显:" + string + "\r\n") printWriter.flush() }} catch (IOException e) { }} }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)