📄 commonmethod.cs
字号:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace mychat1
{
public class commonmethod
{
public static string serverip="192.168.1.2";
public static int port = 9050;
public static void sendtoserver(string str)
{
TcpClient server;
try
{
server = new TcpClient(serverip ,port);
byte[] info = Encoding.Unicode.GetBytes(str);
server.Client.Send(info);
}
catch (SocketException)
{
throw new Exception("unable to connect to server!");
}
server.Close();
}
public static void sendtoserver(string str,out string myownip)
{
TcpClient server;
try
{
server = new TcpClient(serverip, port);
myownip = server.Client.LocalEndPoint.ToString();
byte[] info = Encoding.Unicode.GetBytes(str);
server.Client.Send(info);
}
catch (SocketException)
{
throw new Exception("unable to connect to server!");
}
server.Close();
}
public static void sendtosevermessage(string str)
{
byte[] data = new byte[1024];
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(serverip), 9053);
data =Encoding .Unicode .GetBytes (str);
server.SendTo(data, data.Length, SocketFlags.None, ipep);
server.Close();
}
public static string receiverfromserver(string myownip,out string hername)
{
string stringdata = null;
int recv = 0;
byte[] data = new byte[1024];
string[] mine = myownip.Split(':');
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(mine[0]), Convert.ToInt32(mine[1]));
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
newsock.Bind(ipep);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
recv = newsock.ReceiveFrom(data, ref Remote);
newsock.Close();
stringdata = Encoding.Unicode.GetString(data, 0, recv);
string[] hernames = stringdata.Split(' ');
hername = hernames[0];
return stringdata;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -